Python Road Fortress Machine Paramiko

Source: Internet
Author: User

Paramiko

1. Installation

PIP3 Install Paramiko

Second, use

Sshclient

Used to connect to a remote server and execute basic commands

Connect based on user name password:

Import Paramiko   # SSH object created ssh = Paramiko. Sshclient () # allows connections to host Ssh.set_missing_host_key_policy (Paramiko) that are not in the Know_hosts file. Autoaddpolicy ()) # Connection Server Ssh.connect (hostname= ' c1.salt.com ', port=22, username= ' Wupeiqi ', password= ' 123 ')   # Execute command stdin, stdout, stderr = Ssh.exec_command (' ls ') # get command result = Stdout.read ()   # Close Connection ssh.close ()
#SSHClient package Transportimport Paramikotransport = Paramiko. Transport (' hostname ', ()) Transport.connect (username= ' Wupeiqi ', password= ' 123 ') ssh = Paramiko. Sshclient () Ssh._transport = Transportstdin, stdout, stderr = Ssh.exec_command (' df ') print stdout.read () transport.close ()

connection based on public key:

Import Paramiko  Private_key = Paramiko. Rsakey.from_private_key_file ('/home/auto/.ssh/id_rsa ')  # create ssh object ssh = Paramiko. Sshclient () # allows connections to host Ssh.set_missing_host_key_policy (Paramiko) that are not in the Know_hosts file. Autoaddpolicy ()) # Connection Server Ssh.connect (hostname= ' c1.salt.com ', port=22, username= ' Wupeiqi ', Key=private_key)  # Execute command stdin, stdout, stderr = Ssh.exec_command (' df ') # get command result = Stdout.read ()  # Close Connection ssh.close ()
#SSHClient package Transportimport Paramikoprivate_key = Paramiko. Rsakey.from_private_key_file ('/home/auto/.ssh/id_rsa ') transport = Paramiko. Transport (' hostname ', ()) Transport.connect (username= ' Wupeiqi ', pkey=private_key) ssh = Paramiko. Sshclient () Ssh._transport = Transportstdin, stdout, stderr = Ssh.exec_command (' df ') transport.close ()

sftpclient

For connecting to a remote server and performing an upload download

Upload and download based on user name password:

Import Paramiko  transport = Paramiko. Transport (' hostname ', ()) Transport.connect (username= ' Wupeiqi ', password= ' 123 ')  sftp = Paramiko. Sftpclient.from_transport (transport) # upload location.py to Server/tmp/test.pysftp.put ('/tmp/location.py ', '/tmp/test.py ') # download Remove_path to local local_pathsftp.get (' Remove_path ', ' Local_path ')  transport.close ()

upload and download based on public key keys:

Import Paramiko  Private_key = Paramiko. Rsakey.from_private_key_file ('/home/auto/.ssh/id_rsa ')  transport = Paramiko. Transport (' hostname ', ()) Transport.connect (username= ' Wupeiqi ', pkey=private_key)  sftp = Paramiko. Sftpclient.from_transport (transport) # upload location.py to Server/tmp/test.pysftp.put ('/tmp/location.py ', '/tmp/test.py ') # download Remove_path to local local_pathsftp.get (' Remove_path ', ' Local_path ')  transport.close ()

#!/usr/bin/env python#-*-coding:utf-8-*-import paramikoimport uuidclass sshconnection (object): Def __init__ (self, ho St= ' 172.16.103.191 ', port=22, username= ' Wupeiqi ', pwd= ' 123 '): Self.host = host Self.port = Port self.u Sername = Username Self.pwd = pwd Self.__k = None def create_file (self): file_name = str (uuid.uuid 4 ()) with open (file_name, ' W ') as F:f.write (' SB ') return file_name def run: Self. Connect () self.upload ('/home/wupeiqi/tttttttttttt.py ') self.rename ('/home/wupeiqi/tttttttttttt.py ', '/home/w upeiqi/ooooooooo.py) self.close () def Connect (self): transport = Paramiko. Transport ((Self.host,self.port)) Transport.connect (USERNAME=SELF.USERNAME,PASSWORD=SELF.PWD) Self.__transpor T = Transport def close (self): Self.__transport.close () def upload (Self,target_path): # Connect, upload F Ile_name = Self.create_file () sftp = Paramiko. SFTpclient.from_transport (self.__transport) # upload location.py to server/tmp/test.py sftp.put (file_name, Target_path ) def rename (self, Old_path, new_path): SSH = Paramiko.        Sshclient () Ssh._transport = self.__transport # execute command cmd = "mv%s%s"% (Old_path, New_path,)        stdin, stdout, stderr = Ssh.exec_command (cmd) # gets the command result = Stdout.read () def cmd (self, command): SSH = Paramiko. Sshclient () Ssh._transport = self.__transport # Execute command stdin, stdout, stderr = ssh.exec_command (command # get Command result = Stdout.read () return result ha = Sshconnection () ha.run ()

# For more restriction commands, you need to set/etc/sudoers Defaults Requirettydefaults:cmdb in the system    !requiretty

Import Paramikoimport Uuidclass sshconnection (object): Def __init__ (self, host= ' 192.168.11.61 ', port=22, Username= ' ale        X ', pwd= ' alex3714 '): self.host = host Self.port = Port Self.username = Username Self.pwd = pwd        Self.__k = None def run (self): Self.connect () pass Self.close () def Connect (self): Transport = Paramiko. Transport ((Self.host,self.port)) Transport.connect (USERNAME=SELF.USERNAME,PASSWORD=SELF.PWD) Self.__transpor T = Transport def close (self): Self.__transport.close () def-cmd (self, command): SSH = Paramiko. Sshclient () Ssh._transport = self.__transport # Execute command stdin, stdout, stderr = ssh.exec_command (command  # get Command result = Stdout.read () return result def upload (Self,local_path, target_path): # Connect, upload sftp = Paramiko. Sftpclient.from_transport (self.__transport) # upload location.py to server/tmp/test.py sftp.put(Local_path, target_path) ssh = Sshconnection () ssh.connect () r1 = ssh.cmd (' df ') ssh.upload (' s2.py ', "/home/alex/s7.py") Ssh.close ()
Fortress machine
Import paramikoimport sysimport osimport socketimport getpassfrom paramiko.py3compat import u# Windows does not has Termi Os...try:import Termios Import TTY Has_termios = trueexcept Importerror:has_termios = falsedef interactive_s Hell (chan): If Has_termios:posix_shell (chan) Else:windows_shell (chan) def Posix_shell (Chan): Impor T Select oldtty = termios.tcgetattr (Sys.stdin) Try:tty.setraw (Sys.stdin.fileno ()) Tty.setcbreak (SYS.S        Tdin.fileno ()) chan.settimeout (0.0) log = open (' Handle.log ', ' A + ', encoding= ' utf-8 ') flag = False Temp_list = [] While True:r, W, E = Select.select ([Chan, Sys.stdin], [], []) if Chan in                        r:try:x = U (CHAN.RECV (1024x768)) If Len (x) = = 0: Sys.stdout.write (' \r\n*** eof\r\n ') break if Flag:if x.     StartsWith (' \ r \ n '):                       Pass Else:temp_list.append (x) Flag = False sys.stdout.write (x) Sys.stdout.flush () except Socke T.timeout:pass if sys.stdin in r:x = Sys.stdin.read (1) impor                 T json if Len (x) = = 0:break if x = = ' \ t ': flag = True Else:temp_list.append (x) if x = = ' \ R ': Log.write ('. Join (Temp_list)) Log.flush () temp_list.clear () chan.send (x) finall Y:termios.tcsetattr (Sys.stdin, Termios. Tcsadrain, Oldtty) def Windows_shell (Chan): Import threading Sys.stdout.write ("Line-buffered terminal emulation. Press F6 or ^z to send eof.\r\n\r\n ") def writeall (sock): while true:data = sock.recv if not data:sys.stdout.write (' \r\n*** EOF ***\r\n\r\n ') sys.stdout.flu SH () break sys.stdout.write (data) Sys.stdout.flush () writer = Threading.            Thread (Target=writeall, Args= (chan)) Writer.start () try:while true:d = Sys.stdin.read (1) If not d:break chan.send (d) except Eoferror: # user hits ^z or F6 passdef Run (): Default_username = Getpass.getuser () Username = input (' username [%s]: '% default_username ') If Len (Usernam e) = = 0:username = default_username hostname = input (' hostname: ') If LEN (hostname) = = 0:print (' * * *        Hostname required. ') Sys.exit (1) tran = Paramiko. Transport ((hostname,,)) tran.start_client () Default_auth = "P" auth = input (' Auth by (p) Assword or (r) SA key[% S] '% Default_auth) if Len (auth) = = 0:auth = Default_auth if auth = = ' R ': DEfault_path = Os.path.join (os.environ[' HOME '), '. SSH ', ' id_rsa ') path = input (' RSA key [%s]: '% Default_path ') If len (path) = = 0:path = Default_path Try:key = Paramiko. Rsakey.from_private_key_file (path) except Paramiko. Passwordrequiredexception:password = Getpass.getpass (' RSA key password: ') key = Paramiko. Rsakey.from_private_key_file (path, password) Tran.auth_publickey (username, key) ELSE:PW = Getpass.getpas    S (' Password for%[email protected]%s: '% (username, hostname)) Tran.auth_password (username, PW) # Open a channel Chan = Tran.open_session () # Gets a terminal chan.get_pty () # activator Chan.invoke_shell () Interactive_shell (Chan) c Han.close () tran.close () if __name__ = = ' __main__ ': Run ()

Python Road Fortress Machine Paramiko

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.