远程执行命令:paramiko

paramiko模块用于通过 ssh 登录到远程客户端主机并执行命令,常见用法如下:

[root@localhost ~]$ yum install -y python-paramiko


通过用户名密码登录远程客户端主机并执行命令:

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import paramiko

ssh = paramiko.SSHClient()                                                          # 创建一个ssh客户端对象
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())                           # 设置以什么方式连接远程客户端,这里配置自动协商
ssh.connect(hostname='192.168.216.130', port=22, username='root', password='root')  # 通过账号密码连接远程客户端
stdin, stdout, stderr = ssh.exec_command('date')                                    # 远程执行命令,结果会返回标准输入、标准输出、标准错误输出
print stdout.read()                                                                 # 查看执行结果
ssh.close() # 关闭连接
[root@localhost ~]$ python 1.py 
2019年 01月 29日 星期二 06:38:38 CST


通过密钥登录远程客户端主机并执行命令:

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import paramiko

ssh = paramiko.SSHClient()                                          # Create a new SSHClient
key = paramiko.RSAKey.from_private_key_file('/root/.ssh/id_rsa')    # Create a key object by reading a private key file
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())           # Set the policy to use when connecting to a server
ssh.connect(hostname='192.168.216.130', username='root', pkey=key)  # Connect to an SSH server and authenticate to it
stdin, stdout, stderr = ssh.exec_command('date')                    # Execute a command on the SSH server
print stdout.read()
ssh.close() 
[root@localhost ~]$ python 1.py 
2017年 06月 02日 星期五 23:26:08 CST


通过密钥登录远程客户端主机并上传下载文件:

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import paramiko

t = paramiko.Transport(('192.168.216.130', 22))    # Create a Transport object
key = paramiko.RSAKey.from_private_key_file('/root/.ssh/id_rsa')
t.connect(username='root', pkey=key)
sftp = paramiko.SFTPClient.from_transport(t)    # Create an SFTP client channel from an open Transport 
sftp.get('/etc/passwd', '/tmp/passwd')          # 下载文件,把远程客户端的/etc/passwd下载到本地/tmp/passwd
sftp.put('/etc/passwd', '/tmp/passwd')          # 上传文件,把本地/etc/passwd上传到远程客户端的/tmp/passwd
t.close() 

     

猜你喜欢

转载自www.cnblogs.com/pzk7788/p/10356937.html