Python's Paramiko Remote execution command

Source: Internet
Author: User
Tags python script

Sometimes it is necessary to execute a command on a remote machine and get its return result. In this case, Python can be easily implemented.

1. Tools

Python Paramiko

1) Paramiko Module installation

In Linux terminal, enter the PIP install Paramiko command directly.

2) determine Paramiko installation success

Enter import Paramiko on the Python command line to verify that the installation was successful and that no error was made.

2. Steps

1. Import Paramiko Module

# !/usr/bin/python Import Paramiko

2. Create SSH connection function

def Ssh_connect (_host, _username, _password):     Try :         = Paramiko. Sshclient ()        _ssh_fd.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())        = _username, password = _password)    except  Exception, E:         Print ' ssh%[email protected]%s:%s ' % (_username, _host, E))        exit ()    return _ssh_fd

3. Create a command execution function

def ssh_exec_cmd (_SSH_FD, _cmd):     return _ssh_fd.exec_command (_cmd)

4. Create a close SSH function

def Ssh_close (_SSH_FD):    _ssh_fd.close ()

5. Examples of Use

defMain (): hostname='192.168.1.222'Port= 22username='Root'Password='[email protected]'cmd="ps-ef|grep Java"sshd=Ssh_connect (hostname, username, password) stdin, stdout, stderr=ssh_exec_cmd (sshd, cmd) err_list=Stderr.readlines ()ifLen (err_list) >0:Print 'ERROR:'+Err_list[0] Exit () forIteminchstdout.readlines ():PrintItem, Ssh_close (sshd)if __name__=="__main__": Main ()

If the execution script succeeds, the following results are returned successfully.

Root 2540 2536 2 14:13 pts/4 00:01:21 java-ddefault.client.encoding=utf-8-dfile.encoding=utf-8-Duser.language =zh-duser.region=cn-duser.timezone=gmt+08Cn.com.ctsi.csdp.resource.Approot3442 3387 0 2016? 01:09:00 java-ddefault.client.encoding=utf-8-dfile.encoding=utf-8-DUSER.LANGUAGE=ZH-DUSER.REGION=CN- duser.timezone=gmt+08Cn.com.ctsi.csdp.product.Approot3451 3390 0 2016? 01:04:54 java-ddefault.client.encoding=utf-8-dfile.encoding=utf-8-DUSER.LANGUAGE=ZH-DUSER.REGION=CN- duser.timezone=gmt+08Cn.com.ctsi.csdp.report.Approot3452 3388 0 2016? 00:51:00 java-ddefault.client.encoding=utf-8-dfile.encoding=utf-8-DUSER.LANGUAGE=ZH-DUSER.REGION=CN- duser.timezone=gmt+08Cn.com.ctsi.csdp.workflow.launcher.Approot3892 3886 0 2016? 00:29:59 java-ddefault.client.encoding=utf-8-dfile.encoding=utf-8-DUSER.LANGUAGE=ZH-DUSER.REGION=CN- duser.timezone=gmt+08Cn.com.ctsi.csdp.charge.Approot4509 4507 0 15:09? 00:00:00 bash-c ps-ef|grep javaroot4519 4509 0 15:09? 00:00:00grep javaroot12861 12857 0 Jan06? 00:09:06 java-ddefault.client.encoding=utf-8-dfile.encoding=utf-8-DUSER.LANGUAGE=ZH-DUSER.REGION=CN- duser.timezone=gmt+08Cn.com.ctsi.csdp.workorder.Approot16484 16480 0 2016? 00:45:27 java-ddefault.client.encoding=utf-8-dfile.encoding=utf-8-DUSER.LANGUAGE=ZH-DUSER.REGION=CN- duser.timezone=gmt+08Cn.com.ctsi.csdp.billing.Approot18699 18694 0 Jan06? 00:09:30 java-ddefault.client.encoding=utf-8-dfile.encoding=utf-8-DUSER.LANGUAGE=ZH-DUSER.REGION=CN- duser.timezone=gmt+08Cn.com.ctsi.csdp.order.Approot21902 21898 0 Jan05? 00:18:46 java-ddefault.client.encoding=utf-8-dfile.encoding=utf-8-DUSER.LANGUAGE=ZH-DUSER.REGION=CN- duser.timezone=gmt+08 cn.com.ctsi.csdp.user.launcher.App

In real-world development, you need to use PS-EF every time you update a module's jar package | grep Java, view the module's process number, then use the command kill-9 process number, process the process off, and then restart the module.

Here's an attempt to use a Python script instead of manually entering code.

3. Example

1) Boot module

#-*-coding:utf-8-*-ImportParamikossh=Paramiko. Sshclient () Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) Ssh.connect ('192.168.1.222', username ='Root', password ='[email protected]', timeout = 5) cmd='nohup/csdp/charge_launcher-1.0-release/bin/run.sh >/csdp/charge_launcher-1.0-release/bin/nohup.out 2> &1 & \ r \ n'Password='[email protected]'stdin, stdout, stderr=Ssh.exec_command (cmd)##stdin, stdout, stderr = Ssh.exec_command (' sudo-s%s\n '% cmd)##stdin. Write ('%s\r\n '% password)##stdin. Flush ()Print "------------------------"##print stdout.readlines ()##print stderr.read ()Print "------------------------"cmd='pwd'stdin, stdout, stderr=Ssh.exec_command (cmd)Printstdout.readlines () ssh.close ( )

2) Upload files remotely

#-*-coding:utf-8-*-ImportParamikoserverip='192.168.55.243'Serveruser='Root'serverpwd='[email protected]'LocalFile='User-1.0-release.jar'LocalPath= R'D:\workspace\csdp201512041\csdp-ningxia\csdp_user\user\target'+ Os.sep +Localfileremotepath='/csdp/user_launcher-1.0-dev/lib/'+LocalFiledefftpmodulefile (): t= Paramiko. Transport ((ServerIP, 22)) T.connect (username= serveruser, Password =serverpwd) sftp=Paramiko. Sftpclient.from_transport (t)#remotepath= '/csdp/user_launcher-1.0-dev/user-1.0-release.jar '   #localpath= R ' D:\workspace\csdp201512041\csdp-ningxia\csdp_user\user\target\user-1.0-release.jar 'sftp.put (Localpath,remotepath) t.close ()Print(":) successfully uploaded%s file. "%RemotePath)if __name__=='__main__': Ftpmodulefile ()

3) Execute Remote Linux command

#-*-coding:utf-8-*-ImportParamikoif __name__=="__main__": hostname='192.168.55.243'Port= 22username='Root'Password='[email protected]'cmd="ps-ef|grep Java"SSH=Paramiko. Sshclient () Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())#Ssh.connect (hostname, username, password)Ssh.connect (hostname,username=username,password=password,allow_agent=false,look_for_keys=False) stdin, stdout, stderr=ssh.exec_command (cmd) List=Stdout.readlines ()Print(list) ssh.close ()

Python's Paramiko Remote execution command

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.