How to Establish an SSH connection using Python
This example describes how to establish an SSH connection using Python. Share it with you for your reference. The specific implementation method is as follows:
I need to implement a function to remotely connect to the SSH server in Windows to execute commands, so I need to find information online. My environment is Windows 7 64-bit and Python 2.7 32-bit. According to the Internet, you need to download the pycrypto and paramiko modules for installation. The last versions downloaded are pycrypto2.3 and paramiko1.7.6.
The installation process is also relatively simple. install pycrypto and then install paramiko. decompress the package and switch to the decompressed directory at the command prompt. Enter python setup. py install. In addition, install mingw before installing pycrypto. Otherwise, a BAT file is missing because of the lack of a compiler. After mingw is installed, you need to create a distutils. cfg file in the Lib \ distutils \ folder under the Python installation directory. The file content is:
[Build]
Compiler = mingw32
Mingw: http://sourceforge.net/projects/mingw/files/Automated%20MinGW%20Installer/mingw-get-inst/
For the download and installation of pycrypto and paramiko, see install python paramiko module in windows.
After installation, you can write code. Because my SSH server can be connected with only the user name and password, it should be said to be the simplest one.
The following is an example. You can understand it at a Glance:
Stdout. readlines () returns a list. In general, each line output of Linux commands is stored as an element with line breaks.
?
1 2 3 4 5 6 7 8 |
Import paramiko Client = paramiko. SSHClient () Client. set_missing_host_key_policy (paramiko. AutoAddPolicy ()) Client. connect ('1970. 168.8.248 ', 22, username = 'root', password = 'Password', timeout = 4) Stdin, stdout, stderr = client.exe c_command ('LS-l ') For std in stdout. readlines (): Print std, Client. close () |
The output result is:
?
1 2 3 4 5 6 7 |
>>> Total 184804 -Rw ------- 1 root 973 05-19 anaconda-ks.cfg -Rw-r -- 1 root 13895 05-19 20:27 install. log -Rw-r -- 1 root 3058 05-19 20:25 install. log. syslog -Rw-r -- 1 root 189008625 05-28 09:55 tmp >>> |
I hope this article will help you with Python programming.