The python SSH module logs in and the remote machine executes shell command instance resolution
- 2020-06-23 01:09:30
- OfStack
Log in with the python SSH module and execute the shell command on the remote machine
(Successful CentOS 7 environment trial, Redhat series should be compatible.)
Install the necessary modules first
# yum install python-dev
# yum install python-devel
# pip install pycrypto
# pip install paramiko
# pip install ssh
Once these are successful, write an Python script
# vim remote_run.py
import ssh
# new 1 a ssh Client object
myclient = ssh.SSHClient()
# Set to automatically accept the key by default
myclient.set_missing_host_key_policy(ssh.AutoAddPolicy())
# Connect to remote host
myclient.connect("xxx.coder4.com", port=22, username="xxxx", password="xxxx")
# Execute on remote machine shell The command
stdin, stdout, stderr = client.exec_command("ls -l")
# Read return result
print stdout.read()
# Execute on remote machine python The script command
stdin, stdout, stderr = client.exec_command("python /home/test.py")
Once you have created an SSHClient object, you can, in addition to executing commands, turn on an sftp session for transferring files, creating folders, and so on.
# new sftp session
sftp = client.open_sftp()
# Create a directory
sftp.mkdir('abc')
# Download the file from the remote host, if it fails, This might throw an exception.
sftp.get('test.sh', '/home/testl.sh')
# Uploading a file to a remote host may also throw an exception
sftp.put('/home/test.sh', 'test.sh')
conclusion
This is the python SSH module login, remote machine shell command instance analysis, hope to help you. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out. Thank you for your support!