Python uses paramiko to connect to a remote server to execute commands.

Source: Internet
Author: User

Python uses paramiko to connect to a remote server to execute commands.

The paramiko module in python is used to connect to the database on the remote server through ssh. It can be used to execute commands or upload files during connection.

1. Get a connected object.

The following code can be used for connection:

def connect(host):  'this is use 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 name of a host. After this method is executed, If you successfully connect to the server, an sshclient object is returned.

The first step is to create an SSHClient object, and then set the ssh client to allow connections to machines not in the know_host file, and then try to connect to the server. When connecting to the server, you can use either of the following methods: one way is to use the key, that is, the parameter look_for_keys. Here, you can set the password to find the key. You can also directly use the password, that is, directly use the parameter password, finally, a connection object is returned.

2. Get the SET command

After paramiko connection, you must obtain the command to be executed, 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 parameter, one is args, and the other is outpath. args indicates the command parameter, while outpath indicates the path of the executable file, for example,/usr/bin/ls-l. In this example, outpath is/usr/bin/ls, and the parameter is-l.

This method is mainly used to combine commands and assemble separate parameters as part of the commands.

3. execute commands

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

def exec_commands(conn,cmd):  'this is 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, the input parameter is the connected object conn, the command cmd to be executed, and the execution result is obtained, that is, stdout. read (), and finally return the result.

4. upload files

When using a connection object, you can also directly upload related files, as shown in the following functions:

def copy_moddule(conn,inpath,outpath):  'this is copy 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: connection object conn, uploaded file name, and uploaded file name. The complete file name, including the path, must be written here.

The main method is to open an sftp object, use the put Method to upload files, close the sftp connection, and return the complete path of the uploaded file name.

5. Run the command to obtain the result.

Finally, run the command to get the returned result. The Code is as follows:

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, connect to the server and obtain a connection object. If the connection fails, the host name and None are returned, indicating that the connection is successful. If the connection is successful, modify the File Execution permission, in this way, you can execute the file, get the executed command, and finally execute the command to get the result. Return the result in json format, so that the result can be in beautiful json format, finally, related information is returned along 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')

Step 1: Test the command execution, Step 2: Test the file upload, and Step 3: test the File Upload permission.

The complete code is as follows:

#!/usr/bin/env pythonimport jsonimport paramikodef connect(host):  'this is use 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 Nonedef command(args,outpath):  'this is get the command the args to return the command'  cmd = '%s %s' % (outpath,args)  return cmddef exec_commands(conn,cmd):  'this is 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 resultsdef 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)  result = json.dumps(result)  return [host,result]
def copy_module(conn,inpath,outpath):    'this is copy the module to the remote server'    ftp = conn.open_sftp()    ftp.put(inpath,outpath)    ftp.close()    return outpathif __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 main difference is to use the paramiko module in python to connect to the linux server through ssh, then execute the relevant commands and upload the files to the server.

The above python Method of Using paramiko to connect to a remote server to execute commands is all the content that I have shared with you. I hope you can give us a reference and also hope you can provide more support to the customer center.

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.