With Paramiko , you can do a ssh2 secure connection via python, you can also use remote command, file transfer and ssh proxy, etc.
Install paramiko:
To install paramiko, we need the dependencies python-dev ,and modules pycrypto and ecdsa.
apt-get install python-dev
Centos:
yum -y install python-devel
pip install pycrypto ecdsa
Then install paramiko
pip install paramiko
To test the success of the installation:
# python Python 2.6.6 (r266: 84292, Jul 10 2013, 22: 48: 45) [GCC 4.4.7 20120313 (Red Hat 4.4.7-3) ] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import paramiko >>>
If there is no error message, then it means you installed the module successfully.
core class
There are two core classes: SSHClient class and SFTPClient class.
1, SSHClient class
We can use the methods to connect, transport, build channel, and verify.
Here is a simple example:
hostname='192.168.10.110' username='administrator' password='adminpassword' paramiko.util.log_to_file('syslogin.log') #write the paramiko logging to a log file client=SSHClient() #Create a ssh client objectclient.load_system_host_keys() #Get the host key from ./ssh/know_hosts, if the host is not in this file, use following line and comment this line out. client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # Automatically add the unknown host to the known_host client.connect(hostname=hostname, username=username, password=password) stdin, stdout, stderr=client.exec_command('free -m') #execute the command 'free -m' to show the free memory print stdout.read() stdout.readlines() client.close() #terminate the ssh connection
set_missing_host_key_policy(policy) : Set policy to use when connecting to servers without a known host key.
Specifically:
A policy is a “policy class” (or instance thereof), namely some subclass of MissingHostKeyPolicy such as RejectPolicy (the default), AutoAddPolicy, WarningPolicy, or a user-created subclass.
Reference: http://docs.paramiko.org/en/2.4/api/client.html
Parameters: |
|
---|
2. exec_command
Execute a command on the SSH server. A new Channel
is opened and the requested command is executed. The command’s input and output streams are returned as Python file
-like objects representing stdin, stdout, and stderr.
Parameters: |
|
---|---|
Returns: |
the stdin, stdout, and stderr of the executing command, as a 3-tuple |