Python module--paramiko

Source: Internet
Author: User

Tag: Set a nbsp set without setting the key output input

The Paramiko module provides SSH and SFT with the ability to execute commands and upload downloaded files remotely from the server. This is a third-party package that needs to be installed before use.

1 login based on user name and password in sshclient mode

#Create a Sshclient objectSSH =Paramiko. Sshclient ()#allows trusted hosts to be automatically added to the Host_allow list, which must be placed in front of the Connect methodSsh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())#Call The Connect method to connect to the serverSsh.connect (hostname='192.168.2.129', Port=22, Username='Super', password='Super')#Execute Commandstdin, stdout, stderr = Ssh.exec_command ('Df-hl')#The result is put in stdout, if there is an error will be put into stderrPrint(Stdout.read (). Decode ())#Close ConnectionSsh.close ()

2 login based on user name and password in transport mode
Method 1 is a traditional connection server, execute a command, 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 objecttrans = Paramiko. Transport (('192.168.2.129', 22))#Establish a connectionTrans.connect (username='Super', password='Super')#specifies the transport of the Sshclient object as the TransSSH =Paramiko. Sshclient () Ssh._transport=Trans#execute commands, just like traditional methodsstdin, stdout, stderr = Ssh.exec_command ('Df-hl')Print(Stdout.read (). Decode ())#Close ConnectionTrans.close ()

3 sshclient mode login based on public key

#Specifies the local RSA private key file, if a password is set when setting the key pair, password is the set password, such as without specifying the password parameterPkey = Paramiko. Rsakey.from_private_key_file ('/home/super/.ssh/id_rsa', password='12345')#Establish a connectionSSH =Paramiko. Sshclient () Ssh.connect (hostname='192.168.2.129', Port=22, username='Super', Pkey=Pkey)#Execute Commandstdin, stdout, stderr = Ssh.exec_command ('Df-hl')#The result is put in stdout, if there is an error will be put into stderrPrint(Stdout.read (). Decode ())#Close ConnectionSsh.close ()

4 Key-based Transport mode login

#Specifies the local RSA private key file, if a password is set when setting the key pair, password is the set password, such as without specifying the password parameterPkey = Paramiko. Rsakey.from_private_key_file ('/home/super/.ssh/id_rsa', password='12345')#Establish a connectiontrans = Paramiko. Transport (('192.168.2.129', 22)) Trans.connect (username='Super', pkey=Pkey)#specifies the transport of the Sshclient object as the TransSSH =Paramiko. Sshclient () Ssh._transport=Trans#execute commands, just like traditional methodsstdin, stdout, stderr = Ssh.exec_command ('Df-hl')Print(Stdout.read (). Decode ())#Close ConnectionTrans.close ()

##### file SFTP ###########

#Instantiate a Trans object # Instantiate a transport objecttrans = Paramiko. Transport (('192.168.2.129', 22))#Establish a connectionTrans.connect (username='Super', password='Super')#instantiate an Sftp object that specifies the connected channelSFTP =Paramiko. Sftpclient.from_transport (trans)#Send FileSftp.put (localpath='/tmp/11.txt', remotepath='/tmp/22.txt')#Download File#Sftp.get (RemotePath, LocalPath)Trans.close ()

5 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:

ImportParamikoImportOSImportSelectImportSYS#Create a sockettrans = Paramiko. Transport (('192.168.2.129', 22))#Start a clienttrans.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) trans.auth_publickey (username= ' super ', Key=prikey)" "#If you are logged in with a user name and passwordTrans.auth_password (username='Super', password='Super')#Open a channelChannel =trans.open_session ()#Get terminalChannel.get_pty ()#activate the terminal so that you can log in to the terminal, just as we do with the Xshell login systemChannel.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 . whiletrue:readlist, writelist, Errlist=Select.select ([Channel, Sys.stdin,], [], [])#If the user entered the command, the Sys.stdin changed.    ifSys.stdininchreadlist:#Get what you have enteredInput_cmd = Sys.stdin.read (1)        #Send commands to the serverChannel.sendall (input_cmd)#The server returns the results, the channel channels receive the results, and the Select senses to    ifChannelinchreadlist:#Get Resultsresult = CHANNEL.RECV (1024)        #exit after disconnecting        ifLen (Result) = =0:Print("\r\n**** EOF * * \ n")             Break        #Output to screenSys.stdout.write (Result.decode ()) Sys.stdout.flush ()#Close Channelchannel.close ()#Close LinkTrans.close ()

6 Support tab Auto-completion

ImportParamikoImportOSImportSelectImportSYSImportTTYImportTermios" "realize the effect of a Xshell login system, log in to the system to enter the command and return the results to support auto-completion, directly call the server terminal" "#Create a sockettrans = Paramiko. Transport (('192.168.2.129', 22))#Start a clienttrans.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) trans.auth_publickey (username= ' super ', Key=prikey)" "#If you are logged in with a user name and passwordTrans.auth_password (username='Super', password='Super')#Open a channelChannel =trans.open_session ()#Get terminalChannel.get_pty ()#activate the terminal so that you can log in to the terminal, just as we do with the Xshell login systemChannel.invoke_shell ()#get the original operation Terminal PropertiesOldtty =termios.tcgetattr (Sys.stdin)Try:    #set the current Operation terminal property to the native terminal property on the server, which can support tabTty.setraw (Sys.stdin) channel.settimeout (0) whiletrue:readlist, writelist, Errlist=Select.select ([Channel, Sys.stdin,], [], [])#If the user entered the command, the Sys.stdin changed.        ifSys.stdininchreadlist:#get input, enter a word character send 1 charactersInput_cmd = Sys.stdin.read (1)            #Send commands to the serverChannel.sendall (input_cmd)#The server returns the results, the channel channels receive the results, and the Select senses to        ifChannelinchreadlist:#Get Resultsresult = CHANNEL.RECV (1024)            #exit after disconnecting            ifLen (Result) = =0:Print("\r\n**** EOF * * \ n")                 Break            #Output to screenSys.stdout.write (Result.decode ()) Sys.stdout.flush ()finally:    #Restore the current terminal properties to the original terminal properties after executiontermios.tcsetattr (Sys.stdin, Termios. Tcsadrain, Oldtty)#Close Channelchannel.close ()#Close LinkTrans.close ()

Python module--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.