Python's Paramiko module

Source: Internet
Author: User

Introduced

Paramiko is an SSH-based connection to a remote server and performs related operations (Sshclient and Sftpclinet, one is a remote connection, one is an upload download service), which can be used to command or file operations on a remote server, and it is worth saying that The remote management of fabric and ansible is the use of Paramiko to reality.

Installation

The Paramiko module is internally dependent on Pycrypto, so download the installation Pycrypto First, then install Paramiko

Module use  

Sshclient:

The remote connection is divided into two types: (1) connection based on username and password (2) based on public key key connection

Through the use of Paramiko remote operation, in fact, the essence is divided into two types: (1) only use Sshclient (2) to create a transport

(1) Sshclient connection based on user name and password

Import paramiko# creates a Sshclient object Ssh=paramiko. Sshclient () # The host that will connect to the Host_allow trust list, this method must be placed in front of the Connect method Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) # Call the Connect Method connection server Ssh.connect (hostname= ' 192.168.2.129 ', port=22, username= ' super ', password= ' super ') #执行命令stdin, stdout, stderr = Ssh.exec_command (' Df-hl ') # results are placed in stdout, if an error is placed in stderr print (str (stdout.read (), encoding= ' Utf-8 ')) Ssh.close ()

Transport connection based on user name and password

The above method is a traditional connection server, execute commands, close an operation, sometimes need to log on to the server to perform multiple operations, such as executing commands, upload/download files, Method 1 is not implemented, can be done by the following ways

# Instantiate a Transport object trans = Paramiko. Transport (' 192.168.2.129 ', 22) # Build Connection Trans.connect (username= ' super ', password= ' super ') # Specifies the transport of the Sshclient object as the TRANSSSH = Paramiko above. Sshclient () Ssh._transport = trans# Executes the command, like the traditional method stdin, stdout, stderr = Ssh.exec_command (' Df-hl ') print (Stdout.read (). Decode ()) # Close Connection Trans.close ()

(2) Sshclient connection based on secret key

# Specifies the local RSA private key file, if a password is set when establishing a key pair, password is the set password, such as without specifying the password parameter Pkey = Paramiko. Rsakey.from_private_key_file ('/home/super/.ssh/id_rsa ', password= ' 12345 ') # establishes a connection to SSH = Paramiko. Sshclient () ssh.connect (hostname= ' 192.168.2.129 ',            port=22,            username= ' super ',            pkey=pkey) # Execute command stdin, stdout, stderr = Ssh.exec_command (' Df-hl ') # results are placed in stdout, if any errors are placed in the stderr print (Stdout.read (). Decode ()) # Close Connection Ssh.close ()

The above needs to ensure that the server being accessed corresponds to the user. The SSH directory has a Authorized_keys file, which is the public key file generated on the server as Authorized_keys. and use the private key file as the login key for Paramiko.

Transport connection based on secret key

# Specifies the local RSA private key file, if a password is set when establishing a key pair, password is the set password, such as without specifying the password parameter Pkey = Paramiko. Rsakey.from_private_key_file ('/home/super/.ssh/id_rsa ', password= ' 12345 ') # establishes a connection to trans = Paramiko. Transport ((' 192.168.2.129 ', ') ') trans.connect (username= ' super ', Pkey=pkey) # Specify Sshclient object Transport as above Transssh = Paramiko. Sshclient () Ssh._transport = trans# Executes the command, like the traditional method stdin, stdout, stderr = Ssh.exec_command (' Df-hl ') print (Stdout.read (). Decode ()) # Close Connection Trans.close ()

(3) File upload

# Instantiate a Trans object # instantiate a Transport object trans = Paramiko. Transport (' 192.168.2.129 ', 22) # Establishes a connection trans.connect (username= ' super ', password= ' super ') # instantiates an Sftp object, specifying the connected channel SFTP = Paramiko. Sftpclient.from_transport (trans) # Send file Sftp.put (localpath= '/tmp/11.txt ', remotepath= '/tmp/22.txt ') # download File # sftp.get ( RemotePath, LocalPath) trans.close ()

The ability to implement input commands to return results immediately
The above operations are basic connections, if we want to implement a similar Xshell tool function, login can enter the command after the return of the result:

1 ImportParamiko2 ImportOS3 ImportSelect4 ImportSYS5 6 #Create a socket7trans = Paramiko. Transport (('192.168.2.129', 22))8 #Start a client9 trans.start_client ()Ten  One #if you log in with an RSA key A " " - default_key_file = os.path.join (os.environ[' HOME '], '. SSH ', ' id_rsa ') - Prikey = Paramiko. Rsakey.from_private_key_file (Default_key_file) the Trans.auth_publickey (username= ' super ', Key=prikey) - " " - #If you are logged in with a user name and password -Trans.auth_password (username='Super', password='Super') + #Open a channel -Channel =trans.open_session () + #Get terminal A Channel.get_pty () at #activate the terminal so that you can log in to the terminal, just as we do with the Xshell login system - Channel.invoke_shell () - #below you can do all of your operations, using Select to implement - #the input terminal sys.stdin and channels are monitored, - #when the user enters a command in the terminal, the command is handed over to the channel, and this time the Sys.stdin is changed, and select can perceive - #the sending and receiving of the channel is actually the process of sending and accepting information from a socket . in  whileTrue: -ReadList, writelist, errlist =Select.select ([Channel, Sys.stdin,], [], []) to     #If the user entered the command, the Sys.stdin changed. +     ifSys.stdininchreadlist: -         #Get what you have entered theInput_cmd = Sys.stdin.read (1) *         #Send commands to the server $ Channel.sendall (input_cmd)Panax Notoginseng  -     #The server returns the results, the channel channels receive the results, and the Select senses to the     ifChannelinchreadlist: +         #Get Results Aresult = CHANNEL.RECV (1024) the         #exit after disconnecting +         ifLen (Result) = =0: -             Print("\r\n**** EOF * * \ n") $              Break $         #Output to screen - Sys.stdout.write (Result.decode ()) - Sys.stdout.flush () the  - #Close ChannelWuyi channel.close () the #Close Link -Trans.close ()
View Code

Support Tab Auto-completion

1 ImportParamiko2 ImportOS3 ImportSelect4 ImportSYS5 ImportTTY6 ImportTermios7 8 " "9 Implement a Xshell login system effect, log on to the system and continue to enter the command and return resultsTen Support Auto-completion, direct call to server terminal One  A " " - #Create a socket -trans = Paramiko. Transport (('192.168.2.129', 22)) the #Start a client - trans.start_client () -  - #if you log in with an RSA key + " " - default_key_file = os.path.join (os.environ[' HOME '], '. SSH ', ' id_rsa ') + Prikey = Paramiko. Rsakey.from_private_key_file (Default_key_file) A Trans.auth_publickey (username= ' super ', Key=prikey) at " " - #If you are logged in with a user name and password -Trans.auth_password (username='Super', password='Super') - #Open a channel -Channel =trans.open_session () - #Get terminal in Channel.get_pty () - #activate the terminal so that you can log in to the terminal, just as we do with the Xshell login system to Channel.invoke_shell () +  - #get the original operation Terminal Properties theOldtty =termios.tcgetattr (Sys.stdin) * Try: $     #set the current Operation terminal property to the native terminal property on the server, which can support tabPanax Notoginseng Tty.setraw (Sys.stdin) - channel.settimeout (0) the  +      whileTrue: AReadList, writelist, errlist =Select.select ([Channel, Sys.stdin,], [], []) the         #If the user entered the command, the Sys.stdin changed. +         ifSys.stdininchreadlist: -             #get input, enter a word character send 1 characters $Input_cmd = Sys.stdin.read (1) $             #Send commands to the server - Channel.sendall (input_cmd) -  the         #The server returns the results, the channel channels receive the results, and the Select senses to -         ifChannelinchreadlist:Wuyi             #Get Results theresult = CHANNEL.RECV (1024) -             #exit after disconnecting Wu             ifLen (Result) = =0: -                 Print("\r\n**** EOF * * \ n") About                  Break $             #Output to screen - Sys.stdout.write (Result.decode ()) - Sys.stdout.flush () - finally: A     #Restore the current terminal properties to the original terminal properties after execution + termios.tcsetattr (Sys.stdin, Termios. Tcsadrain, Oldtty) the  - #Close Channel $ channel.close () the #Close Link theTrans.close ()
View Code

Python's Paramiko module

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.