Home  >  Article  >  Backend Development  >  python learning diary (50)--paramiko

python learning diary (50)--paramiko

PHP中文网
PHP中文网Original
2017-06-23 11:55:262789browse

python通过paramiko实现,ssh功能
import paramiko
ssh =paramiko.SSHClient()#创建一个SSH连接对象
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())#允许连接不在KNOV_HOSTs文件中的主机 自动添加
ssh.connect(hostname='192.168.11.51',port=22,username='yjj',password='yjj')#连接,主机 端口  用户名 密码
stdin,stdout,stderr=ssh.exec_command('df')#.exec_command 为执行命令,返回结果  ,标准输入,标准输出,标准错误,错误与输出只会返回其一
result=stdout.read()#获取结果
#result2=stdin.read()#获取结果
#result3=stderr.read()#获取结果
#print(result,result2,result3)
result=result.decode()
print(result)
ssh.close()#关闭连接

ftp function

import paramiko
#创建一个传输通道对象
transport=paramiko.Transport(('192.168.11.50',22))#传输模块  Transport  服务器地址 端口
transport.connect(username='root',password='yjj')#用户名,,密码
sftp=paramiko.SFTPClient.from_transport(transport)#调用传输方法
sftp.put('test2','/home/yjj/test2')#上传文件 ,本地路径文件  ,服务器的路径文件
sftp.get('/home/yjj/test1','test1')#下载文件 ,服务器的路径文件 ,本地路径文件

For security reasons, plaintext passwords are not used and RSA asymmetric keys are used to log in automatically

Under linux: Generate key

python learning diary (50)--paramiko

Transmit to the server where you want to log in:

python learning diary (50)--paramiko

If the transmission is successful, you can successfully log in to the corresponding user on the server

If you log in to linux from windows

You can copy the private key to windows

Specify the private key through paramiko.RSAKey for access

ssh function:

import paramiko
priv_key=paramiko.RSAKey.from_private_key_file('id_rsa')#指定私钥文件
ssh=paramiko.SSHClient()#生成ssh对象
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())#允许连接不在KNOV_HOSTs文件中的主机 自动添加
ssh.connect(hostname='192.168.11.50',port=22,username='root',pkey=priv_key)#连接,主机 端口  用户名 私钥
stdin,stdout,stderr=ssh.exec_command('df')#.exec_command 为执行命令,返回结果  ,标准输入,标准输出,标准错误,错误与输出只会返回其一
result=stdout.read()#获取结果
result=result.decode()
print(result)
ssh.close()#关闭连接

ftp function:

import paramiko
priv_key=paramiko.RSAKey.from_private_key_file('id_rsa')#指定私钥文件
#创建一个传输通道对象
transport=paramiko.Transport(('192.168.11.50',22))#传输模块  Transport  服务器地址 端口
transport.connect(username='root',pkey=priv_key)#用户名,,私钥
sftp=paramiko.SFTPClient.from_transport(transport)#调用传输方法
sftp.put('test2','/home/yjj/test2-2')#上传文件 ,本地路径文件  ,服务器的路径文件
sftp.get('/home/yjj/test1','test1-2')#下载文件 ,服务器的路径文件 ,本地路径文件
with open('test1-2','r',encoding='utf-8') as f:
    s=f.readlines()
    print(s)

The above is the detailed content of python learning diary (50)--paramiko. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn