Python's Paramiko module
This article is reproduced in https://www.cnblogs.com/breezey/p/6663546.html, if there is infringement, please contact.
Paramiko is a module written in the Python language that follows the SSH2 protocol and supports the connection of remote servers in a way that is encrypted and authenticated. Paramiko supports Linux, Solaris, BSD, MacOS X, Windows and other platforms to connect to another platform via SSH from one platform. With this module, it is convenient to make an SSH connection and SFTP protocol for SFTP file transfer. Paramiko commonly used classes and methods:
1, Sshclient classThe Shclient class is a high-level representation of the SSH service session, encapsulating the checksum of the transport, channel, and sftpclient, and is typically used to execute commands.1) Connect methodConnect (self,hostname,port=22,username=none,password=none,pkey=none,key_filename=none,timeout=none,allow_agent =true,look_for_keys=true,compress=false) Parameter Description: hostname: The host address of the connection destination port: Ports that connect to the directory, Default is 22username: User name password: password Pkey: Private key Method user authentication Key_filename: Private key file name timeout: Connection Timeout allow_agent: Whether SSH proxy is allowed Look_for_ Keys: Whether to allow searching for private key files compress: whether to compress when open2) Exec_command methodExec_command (self,command,bufsize=-1) parameter description: command: Executed instruction bufsize: file buffer size, 1 No Limit3) Load_system_host_keys methodLoad_system_host_keys (self,filename=none) parameter description: FileName: Specifies the public key file for the remote host, which defaults to the Known_hosts file in the. SSH directory4) Set_missing_host_key_policy methodSSH = Paramiko. Sshclient () Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) parameter description: Autoaddpolicy: Automatically add host name and key to local and save, do not rely on Load_system_host_keys () configuration, that is, if there is no public key of the remote host in Known_hosts, The default connection prompts yes/no, automatically yesrejectpolicy: Automatically rejects unknown host name and key, relies on Load_system_host_keys () Warnningplicy: function is the same as Autoaddpolicy, But unknown main opportunity hint yes/no
2, Sftpclient classAccording to the SSH Transfer Protocol SFTP session, remote file upload, download and other operations. 1) From_transport method Classmethod From_transport (cls,t) parameter description: T: an example of an authenticated transport object:
Import paramiko>>> a = Paramiko. Transport ("127.0.0.1″,2222") >>> A.connect (username= "root", password= ' 123456) >>> sftp = Paramiko. Sftpclient.from_transport (a)
2) Put method put (self,localpath,remotepath,callback=none,confirm=true) Parameter description: LocalPath: Upload source file local path RemotePath: Target path callback: Get receive and total transmit bytes confirm: whether the stat () method is called after uploading, to confirm the file size example:
>>> localpath= ' ftp-test.log ' >>> remotepath= '/data/ftp-test.log ' >>> sftp.put ( Localpath,remotepath)
3) Get method Get (self, remotepath, LocalPath, callback=none) parameter description: RemotePath: Remote file to download LocalPath: Local storage path callback: Same Put method 4) Other methods mkdir: Used to create a directory remove: Delete directory rename: Rename stat: Get file information listdir: Get directory List
code ExampleParamiko SSH client:
#!/usr/bin/pythonImportParamikoImportOs,sysssh_host = sys.argv[1] Ssh_port = 22user =‘Root‘Password =‘Xxxxxx‘cmd = sys.argv[2]paramiko.util.log_to_file (‘/tmp/test‘)#Use Paramiko to log s = Paramiko. Sshclient ()# binding an instance S.load_system_host_keys () # load known_hosts file S.set_missing_host_key_policy ( Paramiko. Autoaddpolicy ()) # remote connection if yes/no is prompted, the default is Yess.connect (SSH _host,ssh_port,user,password,timeout=5) # Connect remote host stdin, Stdout,stderr = S.exec_command (cmd) # execute instructions, The command itself and the execution result of the command are assigned to standard, standard output, or standard error Cmd_result = Stdout.read (), Stderr.read () # get executed output for line in Cmd_result: print Lines.close ()
Connect using SSH key:
'/home/breeze/.ssh/id_rsa'key = Paramiko. Rsakey.from_private_key_file (Pkey_file) s.connect (host,port,username,pkey=key,timeout=5) stdin,stdout,stderr = S.exec_command (cmd)
Paramiko sftp Transfer file:
#!/usr/bin/pythonImportOs,sysImportParamikohost = sys.argv[1]rfilename = sys.argv[2]lfilename = Os.path.basename (rfilename) user = ' root " password = ' xxxx ' paramiko.util.log_to_file ( " Span style= "COLOR: #800000" >/tmp/test ") T = Paramiko. Transport ((Host,22password) sftp = Paramiko. Sftpclient.from_transport (t) sftp.get (rfilename,lfilename) # sftp.put (' paramiko1.py ', '/tmp/paramiko1.py ') t.close ()
Use the interactive module for SSH interaction:The contents of the interactive.py module are as follows:
#!/usr/bin/pythonImportSocketImportSys#Windows does not has termios ...Try:ImportTermiosImportTTY Has_termios =TrueExceptImporterror:has_termios =FalseDefInteractive_shell (Chan):IfHas_termios:posix_shell (Chan)Else: Windows_shell (Chan)DefPosix_shell (Chan):ImportSelect Oldtty =Termios.tcgetattr (Sys.stdin)Try: Tty.setraw (Sys.stdin.fileno ()) Tty.setcbreak (Sys.stdin.fileno ()) Chan.settimeout (0.0)WhileTrue:r, W, E =Select.select ([Chan, Sys.stdin], [], [])If ChanInchR:Try: x = CHAN.RECV (1024)If Len (x) = =0:Print‘\r\n*** eof\r\n‘,BreakSys.stdout.write (x) Sys.stdout.flush ()ExceptSocket.timeout:PassIf Sys.stdinInchR:X = Sys.stdin.read (1)If Len (x) = =0:BreakChan.send (x)Finally: Termios.tcsetattr (Sys.stdin, Termios. Tcsadrain, Oldtty)#Thanks to Mike Looijmans for this codeDefWindows_shell (Chan):ImportThreading Sys.stdout.write ("Line-buffered terminal emulation. Press F6 or ^z to send eof.\r\n\r\n")DefWriteall (sock):WhileTrue:data = SOCK.RECV (256)IfNotData:sys.stdout.write (‘\r\n*** EOF ***\r\n\r\n ") Sys.stdout.flush () Breaksys.stdout.write (data) Sys.stdout.flush () writer = Threading. Thread (Target=writeall, Args= Try:while True:d = Sys.stdin.read (1) if not< Span style= "COLOR: #000000" > D:breakchan.send (d) except Eoferror:# user hit ^z or f6pass
The inter_ssh.py interactive script is as follows:
#!/usr/bin/python#_*_coding:utf8_*_ImportParamikoImportInteractive#Record Log Paramiko.util.log_to_file (‘/tmp/test‘)#Establish SSH connection ssh=Paramiko. Sshclient () Ssh.load_system_host_keys () Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) Ssh.connect ('192.168.128.82', port=22,username='root', password='cheyian')# Establish an interactive shell connection channel=Ssh.invoke_shell ()# Create an interactive pipeline Interactive.interactive_shell (channel) # Close connection channel.close () ssh.close ()
The Paramiko module in Python