Log in with the Python SSH module and execute shell commands on the remote machine

Source: Internet
Author: User
Tags create directory stdin python script

Http://blog.sina.com.cn/s/blog_53d874320102vdvu.html

Log in with the Python SSH module and execute shell commands on the remote machine

(in CentOS 7 The environmental test was successful, the 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


After all these successes, write a Python script


# Vim remote_run.py

Import SSH

# Create a new SSH client object

myclient = ssh. Sshclient ()

# Set as default Auto Accept Key

Myclient.set_missing_host_key_policy (SSH. Autoaddpolicy ())

# Connect to remote host

Myclient.connect ("xxx.coder4.com", port=22, username= "xxxx", password= "xxxx")

# Execute SHELL command on remote machine

stdin, stdout, stderr = Client.exec_command ("Ls-l")

# Read Back Results

Print Stdout.read ()

# Execute Python script command on remote machine

stdin, stdout, stderr = Client.exec_command ("python/home/test.py")

After creating a Sshclient object, in addition to executing commands, you can also open a SFTP session for transferring files, creating folders, and so on. # new SFTP Session SFTP = client. Open_sftp () # Create Directory
Sftp. mkdir (' abc ') # Downloads files from a remote host, which may throw an exception if it fails. Sftp. Get (' test.sh ', '/home/testl.sh ') # uploads files to a remote host, or it may throw an exception sftp. Put ('/home/test.sh ', ' test.sh ')

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.