I. Installation of PARAMIKO modules
The Paramiko module relies on the Pycrypto module, and Pycrypto requires the GCC library to compile, although the generic distribution source contains the module. Here, for example, you can complete the installation directly with the following command: CENTOS6
The code is as follows |
Copy Code |
# yum Install gcc python-crypto python-paramiko python-devel-y
|
Windows Edition can install the Windows version of GCC (MINGW), and then edit the installation pycrypto and Paramiko, download Ancheng, run directly python.exe setup.py build and Python.exe setup.py Install is OK.
Second, the Paramiko connection
There are two ways to connect using the Paramiko module, one is through the Paramiko. Sshclient () function, the other is through Paramiko. Transport () function.
Method One:
The code is as follows |
Copy Code |
Import Paramiko SSH = Paramiko. Sshclient () Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) Ssh.connect ("An IP address", 22, "username", "password")
|
The second line of code above is to allow connections to hosts that are not in the Know_hosts file.
Method Two:
The code is as follows |
Copy Code |
Import Paramiko t = Paramiko. Transport (("host", "Port") T.connect (username = "username", password = "password")
|
If you need to provide a key to connect to a remote host, the second line of code above can be changed to:
The code is as follows |
Copy Code |
T.connect (username = "username", password = "password", hostkey= "key")
|
Third, Paramiko SSH connection
Here is a simple function that uses the SSH connection defined by the Paramiko module and executes the command, as follows:
The code is as follows |
Copy Code |
#!/usr/bin/python #-*-Coding:utf-8-*- Import Paramiko #paramiko. Util.log_to_file ('/tmp/sshout ') def ssh2 (Ip,username,passwd,cmd): Try SSH = Paramiko. Sshclient () Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) Ssh.connect (ip,22,username,passwd,timeout=5) Stdin,stdout,stderr = Ssh.exec_command (cmd) # stdin.write ("y") #简单交互, enter ' Y ' Print Stdout.read () # for X in Stdout.readlines (): # print X.strip ("\ n") print '%s\tok\n '% (IP) Ssh.close () Except: print '%s\terror\n '% (IP) SSH2 ("192.168.0.102", "root", "361way", "Hostname;ifconfig") SSH2 ("192.168.0.107", "root", "123456", "Ifconfig") |
The log section of line fourth, which is a bit of information that records SSH connection interactions, can be viewed as a debug-like output that does not normally need to be turned on.
The Stdin.write section is used in interactive situations where interactions can be performed by this command. Note that this may cause ambiguity, where the interaction is not an interaction that occurs during an SSH connection to enter Yes, because the Paramiko module automatically handles yes validation during the connection process. The interaction here is where the following CMD needs to execute the program that might interact with it, which can be used to interact with this parameter.
StdOut standard output, when the output is relatively young, you can read all the output by using read directly, but it is recommended that you do this by reading by rows when the output is relatively long. When read by row, however, there is a newline character at the end of each line, which results in a very unattractive output. String processing can be done by the strip.
In the function call, it should be noted that IP, username, passwd are both string-type, so you need to quote. CMD after execution, if more than one command needs to be manipulated, it needs to be split by semicolons.
Iv. Examples of Paramiko sftp
Example of a single file biography download:
The code is as follows |
Copy Code |
Import Paramiko #建立一个加密的管道 Scp=paramiko. Transport ((' 192.168.0.102 ', 22)) #建立连接 Scp.connect (username= ' root ', password= ' 361way ') #建立一个sftp客户端对象, operation of remote files via SSH transport Sftp=paramiko. Sftpclient.from_transport (SCP) #Copy a remote file (RemotePath) from the "SFTP server to the" Local host Sftp.get ('/root/testfile ', '/tmp/361way ') #Copy a local file (LocalPath) to the SFTP server as RemotePath Sftp.put ('/root/crash-6.1.6.tar.gz ', '/tmp/crash-6.1.6.tar.gz ') Scp.close ()
|
Example of uploading and downloading multiple files in one directory:
The code is as follows |
Copy Code |
#!/usr/bin/env python #-*-Coding:utf-8-*- Import Paramiko,datetime,os Hostname= ' 192.168.0.102 ' Username= ' Root ' Password= ' 361way ' Port=22 Local_dir= '/tmp/getfile ' Remote_dir= '/TMP/ABC ' Try T=paramiko. Transport ((Hostname,port)) T.connect (Username=username,password=password) Sftp=paramiko. Sftpclient.from_transport (t) #files =sftp.listdir (Dir_path) Files=sftp.listdir (Remote_dir) For f in Files: print ' print ' ######################################### ' print ' Beginning to download file from%s%s '% (Hostname,datetime.datetime.now ()) print ' Downloading file: ', Os.path.join (remote_dir,f) Sftp.get (Os.path.join (remote_dir,f), Os.path.join (local_dir,f)) #下载 #sftp. Put (Os.path.join (local_dir,f), Os.path.join (remote_dir,f)) #上传 print ' Download file success%s '% Datetime.datetime.now () print ' print ' ########################################## ' T.close () Except Exception: Print "Connect error!" |
Note: In the directory of all the files in the download or upload of the example, in the case of a directory with nested directories exist, the directory will also be treated as a file, so if you want to be more perfect, you can introduce the Stat module under the S_isdir method to deal with
The Paramiko.transport object also supports connecting by using a socket, as shown in the following example:
code is as follows |
copy code |
Import Paramiko Transport = Paramiko. Transport ((' localhost ')) Transport.connect (username= ' root ', password = ' password ') Sftp = Paramiko. Sftpclient.from_transport (transport) Sftp.get (remotefile,localfile) #如果是上传则用: #sftp. Put (LocalFile, RemoteFile) Transport.close () #用socket连接 Tcpsock = Socket.socket (socket.af_inet,socket. SOCK_STREAM) Tcpsock.settimeout (5) Tcpsock.connect ((ip,22),) SSH = Paramiko. Transport (Tcpsock) Ssh.connect (Username=user,password=password) Sftpconnect=paramiko. Sftpclient.from_transport (SSH) |
V. Using Paramiko to realize the interactive connection of SSH
The following is through the Paramiko module directly with the SSH protocol login to the remote server operation code, here first define a interactive module, the code is as follows:
The code is as follows |
Copy Code |
Import socket Import Sys # Windows does not have Termios ... Try Import Termios Import TTY Has_termios = True Except Importerror: Has_termios = False def Interactive_shell (Chan): If Has_termios: Posix_shell (Chan) Else Windows_shell (Chan) def Posix_shell (Chan): Import Select Oldtty = termios.tcgetattr (Sys.stdin) Try Tty.setraw (Sys.stdin.fileno ()) Tty.setcbreak (Sys.stdin.fileno ()) Chan.settimeout (0.0) While True: R, W, E = Select.select ([Chan, Sys.stdin], [], []) If Chan in R: Try x = CHAN.RECV (1024) If Len (x) = 0: print ' \r\n*** eof\r\n ', Break Sys.stdout.write (x) Sys.stdout.flush () Except Socket.timeout: Pass If Sys.stdin in R: x = Sys.stdin.read (1) If Len (x) = 0: Break Chan.send (x) Finally Termios.tcsetattr (Sys.stdin, Termios. Tcsadrain, Oldtty) # to Mike Looijmans for this code 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 (256) If not data: Sys.stdout.write (' \r\n*** EOF ***\r\n\r\n ') Sys.stdout.flush () 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 hit ^z or F6 Pass |
The code content can be obtained from Paramiko's demo on the GitHub project. Write another ssh_inter.py interactive main program, which reads as follows:
The code is as follows |
Copy Code |
Import Paramiko Import Interactive #记录日志 Paramiko.util.log_to_file ('/tmp/test ') #建立ssh连接 Ssh=paramiko. Sshclient () Ssh.load_system_host_keys () Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) Ssh.connect (' 192.168.0.102 ', port=22,username= ' root ', password= ' xxxxxx ', compress=true) #建立交互式shell连接 Channel=ssh.invoke_shell () #建立交互式管道 Interactive.interactive_shell (channel) #关闭连接 Channel.close () Ssh.close ()
|
The effect is as if we were using SSH to log on as we normally do.
Vi. Summary
Paramiko module is a relatively powerful SSH connection module, the above example only lists some of the simple use of the module, can also use the threading module to block the speed of the program concurrency, but also can use the Configparser module processing configuration files, and we will all IP , user information actions are put into the configuration file, and the Setproctitle module is used to add an easy to distinguish title for the executing program.
Likewise, although the SSH used by the well-known software such as fabric is encapsulated by the Paramiko module, you can still choose not to use it, and you can choose the Pexpect module implementation to encapsulate a simple SSH connection tool, Or use the same fire-salt-ssh module.