Python uses Paramiko to connect to remote servers to execute commands

Source: Internet
Author: User

The Paramiko module in Python is used to implement an SSH connection to a library on a remote server, which can be used to execute commands or to upload files when making a connection.

1. Get a Connected object

When making a connection, you can use the following code:

def Connect (host): ' This is the    Paramiko connect the Host,return conn '    ssh = Paramiko. Sshclient ()    ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())    try:#        ssh.connect (host,username= ' root ', allow_agent=true,look_for_keys=true)        Ssh.connect (host,username= ' root ', password= ' root ', allow_agent=true)        return ssh    except:        return None
In the Connect function, the parameter is the IP address or host name of a host, and after this method is executed, a Sshclient object is returned if the server is successfully connected.

The first step is to establish an Sshclient object, and then set up an SSH client to allow the connection to a machine that is not in the Know_host file, and then try to connect to the server, which can be used in two ways when connecting to the server: One way is to use the secret key, which is the parameter look_for_ Keys, which is used to set the password to find, can also use the password directly, that is, directly using the parameter password, and finally return a connected object.

2. Get commands for settings

After you make a Paramiko connection, you must get the command you want to execute, as shown in the following code:

def command (Args,outpath):    ' This is get the command ' the ' args ' to return the command '    cmd = '%s%s '% (Outpath,args)    return cmd

In the arguments, one is args, one Outpath,args represents the arguments of the command, and Outpath is represented as the path to the executable file, such as/usr/bin/ls-l. In which Outpath is/usr/bin/ls, and the parameter is-l

This method is primarily used to assemble commands, assembling separate parameters as part of the command.


3. Execution of Orders

After the connection, you can execute the command directly, then you have the following function:

def exec_commands (conn,cmd): ' This was use the    conn to excute the CMD and return the results of Excute the command ' 
   
    stdin,stdout,stderr = Conn.exec_command (cmd)    results=stdout.read ()    return results
   
In this function, an incoming parameter is a connected object conn, a command cmd that needs to be executed, and finally the result of execution, that is, Stdout.read (), and finally the resulting result

4. Uploading Files

When using the Connection object, you can also upload the relevant files directly, the following functions:

def copy_moddule (Conn,inpath,outpath): ' This is copy of the module to the    remote server '    FTP = conn.open_sftp ()    Ftp.put (Inpath,outpath)    ftp.close ()    return Outpath

The main parameters of this function are, one is the connection object conn, one is the file name of the upload, and the name of the file after uploading, where the full file name must be written including the path.

The main practice is to open an Sftp object, then use the Put method to upload the file, finally close the SFTP connection, and finally return an uploaded file name full path

5. Execute command to get results

Finally, execute the command, get the result returned, the following code:

def excutor (Host,outpath,args):    conn = connect (host)    if not conn:        return [Host,none]    exec_commands ( Conn, ' chmod +x%s '% outpath)    cmd =command (args,outpath)    result = Exec_commands (conn,cmd)    print '%r '% Result    result = json.loads (result)    return [Host,result]
First, to connect the server, get a Connection object, if the connection is unsuccessful, then return the host name and none, indicating that there is no successful connection, if the connection is successful, then modify the file execution permissions, so that you can execute the file, then get the command executed, finally, execute the command, get the result, Returns the result in JSON format, resulting in an aesthetically pleasing JSON format, with the result of returning the relevant information together with the host name

6. Test code

The test code is as follows:

if __name__ = = ' __main__ ':    print json.dumps (excutor (' 192.168.1.165 ', ' ls ', '-l '), indent=4,sort_keys=true)    Print copy_module (Connect (' 192.168.1.165 '), ' kel.txt ', '/root/kel.1.txt ')    exec_commands (Connect (' 192.168.1.165 '), ' chmod +x%s '% '/root/kel.1.txt ')
The first step is to test the command execution, the second step is to upload the file, and the third Test modifies the permissions to upload the file.

The complete code is as follows:

#!/usr/bin/env pythonimport jsonimport paramikodef Connect (host): ' This was use the Paramiko connect the Host,return con n ' ssh = Paramiko. Sshclient () Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) try:# Ssh.connect (host,username= ' root ', allow_agent=true,look_for_keys=true) Ssh.connect ( Host,username= ' root ', password= ' root ', allow_agent=true) return ssh except:return nonedef command (args,out Path): ' This is get the command ' the ' args ' to return the command ' cmd = '%s%s '% (Outpath,args) return cmddef exec _commands (conn,cmd): ' This was use the conn to excute the CMD and return the results of Excute the command ' STDIN,STD Out,stderr = Conn.exec_command (cmd) results=stdout.read () return resultsdef excutor (host,outpath,args): conn = Co Nnect (host) if not Conn:return [Host,none] #exec_commands (conn, ' chmod +x%s '% outpath) cmd =command (args , Outpath) result = Exec_commands (conn,cmd) result = Json.dumps (result) return [Host,result] 
def copy_module (Conn,inpath,outpath): ' This is copy of the module to the remote server ' FTP = conn.open_sftp () ftp.p UT (Inpath,outpath) ftp.close () return outpathif __name__ = = ' __main__ ': Print json.dumps (' Excutor ', ' ls ', '-l '), indent=4,sort_keys=true) print copy_module (Connect (' 192.168.1.165 '), ' kel.txt ', '/root/kel.1.txt ') exec_ Commands (Connect (' 192.168.1.165 '), ' chmod +x%s '% '/root/kel.1.txt ')

The main thing is to use the Paramiko module in Python to connect to the Linux server via SSH, then execute the relevant commands and upload the files to the server.



Python uses Paramiko to connect to remote servers to execute commands

Large-Scale Price Reduction
  • 59% Max. and 23% Avg.
  • Price Reduction for Core Products
  • Price Reduction in Multiple Regions
undefined. /
Connect with us on Discord
  • Secure, anonymous group chat without disturbance
  • Stay updated on campaigns, new products, and more
  • Support for all your questions
undefined. /
Free Tier
  • Start free from ECS to Big Data
  • Get Started in 3 Simple Steps
  • Try ECS t5 1C1G
undefined. /

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.