Paramiko instance code of python module, pythonparamiko instance
This article focuses on the usage of paramiko In the python module. The specific implementation code is as follows. Let's take a look at it.
The paramiko module provides ssh and sft functions for remote login to the server to execute commands and upload and download files. This is a third-party software package, which must be installed before use.
1. sshclient logon based on user name and password
# Create an sshclient object ssh = paramiko. SSHClient () # allows you to automatically add a trusted host to the host_allow list. This method must be placed before the connect Method for ssh. set_missing_host_key_policy (paramiko. autoAddPolicy () # Call the connect method to connect to the server ssh. connect (hostname = '2017. 168.2.129 ', port = 22, username = 'super', password = 'super') # Run stdin, stdout, stderr = ssh.exe c_command ('df-hl ') # Put the result in stdout. If there is an error, it will be put in stderr print (stdout. read (). decode () # Close the ssh connection. close ()2. user name and password-based transport Login
Method 1 is a traditional operation that connects to the server, executes commands, and closes. Sometimes you need to log on to the server to execute multiple operations, such as executing commands, uploading/downloading files, method 1 cannot be implemented. You can perform the following operations:
# Instantiate a transport object trans = paramiko. transport ('2017. 168.2.129 ', 22) # create a connection to trans. connect (username = 'super', password = 'super') # specify the transport of the sshclient object as transssh = paramiko. SSHClient () ssh. _ transport = trans # Run the command, which is the same as stdin, stdout, stderr = ssh.exe c_command ('df-hl ') print (stdout. read (). decode () # Close the connection to trans. close ()3. SSHClient logon based on public key
# Specify the local RSA private key file. If a password is set when a key pair is created, the password is the set password. For example, the specified password parameter pkey = paramiko is used. RSAKey. from_private_key_file ('/home/super /. ssh/id_rsa ', password = '000000') # create a connection ssh = paramiko. SSHClient () ssh. connect (hostname = '2017. 168.2.129 ', port = 22, username = 'super', pkey = pkey) # Run stdin, stdout, stderr = ssh.exe c_command ('df-hl ') # Put the result in stdout. If there is an error, it will be put in stderr print (stdout. read (). decode () # Close the ssh connection. close ()
Make sure that there is an authorized_keys file under the user. ssh directory of the accessed server, that is, the public key file generated on the server is saved as authorized_keys. Use the private key file as the logon key of paramiko.
4. Key-based Transport Login
# Specify the local RSA private key file. If a password is set when a key pair is created, the password is the set password. For example, the specified password parameter pkey = paramiko is used. RSAKey. from_private_key_file ('/home/super /. ssh/id_rsa ', password = '000000') # create a connection trans = paramiko. transport ('2017. 168.2.129 ', 22) trans. connect (username = 'super', pkey = pkey) # specify the transport of the sshclient object as transssh = paramiko. SSHClient () ssh. _ transport = trans # Run the command, which is the same as stdin, stdout, stderr = ssh.exe c_command ('df-hl ') print (stdout. read (). decode () # Close the connection
##### Transferring files to SFTP ###########
# Instantiate a trans object # instantiate a transport object trans = paramiko. transport ('2017. 168.2.129 ', 22) # create a connection to trans. connect (username = 'super', password = 'super') # instantiate an sftp object and specify the connection channel sftp = paramiko. SFTPClient. from_transport (trans) # Send the sftp file. put (localpath = '/tmp/11.txt', remotepath = '/tmp/22.txt') # download file # sftp. get (remotepath, localpath) trans. close ()5. You can enter a command to immediately return results.
The above operations are basic connections. If we want to implement a function similar to the xshell tool, after logging on, we can enter the command and press enter to return the result:
Import paramikoimport osimport selectimport sys # create a sockettrans = paramiko. transport ('2017. 168.2.129 ', 22) # Start a client trans. start_client () # If you use the rsa key to log on, '''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 use the user name and password to log on to trans. auth_password (username = 'super', password = 'super') # Open a channel = trans. open_session () # obtain the terminal channel. get_pty () # activate the terminal so that you can log on to the terminal, just like using a channel similar to xshell to log on to the system. invoke_shell () # You can execute all your operations below, and use select to implement # On the input terminal sys. stdin and channels are monitored. # When a user enters a command on the terminal, the command is handed over to the channel. At this time, sys. stdin changes, and select can perceive # The sending command of channel and the process of obtaining the result is actually a process of sending and receiving information of socket while True: readlist, writelist, errlist = select. select ([channel, sys. stdin,], [], []) # If the user entered the command, sys. stdin changed if sys. stdin in readlist: # Get the input content input_cmd = sys. stdin. read (1) # send the command to the server channel. sendall (input_cmd) # The server returns the result, the channel receives the result, and the select perceives the if channel in readlist: # obtain the result = channel. recv (1024) # Disconnect and exit if len (result) = 0: print ("\ r \ n ***** EOF ***** \ r \ n ") break # output to the screen sys. stdout. write (result. decode () sys. stdout. flush () # disable channel. close () # close the link trans. close ()6. Support automatic tab completion
Import paramikoimport osimport selectimport sysimport ttyimport termios ''' to implement an xshell logon system. After logging on to the system, you can enter commands and return results to support Automatic completion, directly call the server terminal ''' # create a sockettrans = paramiko. transport ('2017. 168.2.129 ', 22) # Start a client trans. start_client () # If you use the rsa key to log on, '''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 use the user name and password to log on to trans. auth_password (username = 'super', password = 'super') # Open a channel = trans. open_session () # obtain the terminal channel. get_pty () # activate the terminal so that you can log on to the terminal, just like using a channel similar to xshell to log on to the system. invoke_shell () # obtain the original operation terminal attribute oldtty = termios. tcgetattr (sys. stdin) try: # set the current operation terminal attribute to the native terminal attribute on the server. tab is supported for tty. setraw (sys. stdin) channel. settimeout (0) while True: readlist, writelist, errlist = select. select ([channel, sys. stdin,], [], []) # If the user entered the command, sys. stdin changed if sys. stdin in readlist: # Get the input content. Enter one character and send one character. input_cmd = sys. stdin. read (1) # send the command to the server channel. sendall (input_cmd) # The server returns the result, the channel receives the result, and the select perceives the if channel in readlist: # obtain the result = channel. recv (1024) # Disconnect and exit if len (result) = 0: print ("\ r \ n ***** EOF ***** \ r \ n ") break # output to the screen sys. stdout. write (result. decode () sys. stdout. flush () finally: # after execution, restore the current terminal property to the original terminal property termios. tcsetattr (sys. stdin, termios. TCSADRAIN, oldtty) # disable channel. close () # close the link trans. close ()
Summary
The above is all about the paramiko instance code of the python module in this article. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!