Home  >  Article  >  Backend Development  >  Learning sharing about paramiko module in python

Learning sharing about paramiko module in python

黄舟
黄舟Original
2017-08-23 11:38:481305browse

This article mainly shares the learning materials of the python paramiko module with everyone. It has certain reference value. Interested friends can refer to it.

paramiko is a module written in python language. Follow The SSH2 protocol supports encryption and authentication to connect to remote servers. paramiko supports Linux, Solaris, BSD, MacOS X, Windows and other platforms to connect from one platform to another through SSH. Using this module, you can easily perform ssh connection and sftp protocol for sftp file transfer.

First let us clarify the following nouns:

SSHClient: packages Channel, Transport, SFTPClient
Channel: is a Type Socket, a secure SSH transmission channel;
Transport: is an encrypted session (but the Session of such an object is not established), and creates an encrypted tunnels. This tunnels It's called Channel;
Session: is the object that keeps the connection between client and Server. Use connect()/start_client()/start_server() to start the session.

Download and install

pycrypto. Since the paramiko module depends internally on pycrypto, download and install pycrypto first

pip3 install pycrypto
pip3 install paramiko

Specific module usage

SSHClient:

Remote connections are divided into two types: (1) Connection based on username and password (2) Connection based on public key and secret key

Remote operation is done using paramiko. In fact, it is essentially divided into two types: (1) Only use SSHClient (2) Create a transport yourself

Connect based on username and password


import paramiko
 
# 创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname='host', port=22, username='root', password='123')
# 执行命令  stdout命令结果,stderr错误
stdin, stdout, stderr = ssh.exec_command('ls')
# 获取命令结果 
result = stdout.read()
# 关闭连接
ssh.close()

SSHClient encapsulation Transport


import paramiko
 
transport = paramiko.Transport(('hostname', 22))
transport.connect(username='root', password='123')
 
ssh = paramiko.SSHClient()
ssh._transport = transport
 
stdin, stdout, stderr = ssh.exec_command('df')
print(stdout.read())
 
transport.close()

Connect based on public key


##

import paramiko
 
private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa')
# 创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname='host', port=22, username='root', key=private_key)
# 执行命令
stdin, stdout, stderr = ssh.exec_command('df')
# 获取命令结果
result = stdout.read()
# 关闭连接
ssh.close()

SSHClient encapsulates Transport


import paramiko
 
private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa')
transport = paramiko.Transport(('hostname', 22))
transport.connect(username='wupeiqi', pkey=private_key)
ssh = paramiko.SSHClient()
ssh._transport = transport
stdin, stdout, stderr = ssh.exec_command('df')
transport.close()

SFTPClient:

is used to connect to the remote server and perform upload and download functions .

Upload and download based on username and password


import paramiko
 
transport = paramiko.Transport(('hostname',22))
transport.connect(username='root',password='123')
 
sftp = paramiko.SFTPClient.from_transport(transport)
# 将location.py 上传至服务器 /tmp/test.py
sftp.put('/tmp/location.py', '/tmp/test.py')
# 将remove_path 下载到本地 local_path
sftp.get('remove_path', 'local_path')
 
transport.close()

Upload and download based on public key


import paramiko
private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa')

transport = paramiko.Transport(('hostname', 22))
transport.connect(username='root', pkey=private_key )
 
sftp = paramiko.SFTPClient.from_transport(transport)
# 将location.py 上传至服务器 /tmp/test.py
sftp.put('/tmp/location.py', '/tmp/test.py')
# 将remove_path 下载到本地 local_path
sftp.get('remove_path', 'local_path')
 
transport.close()

Demo: Implement remote command execution and file upload


import paramiko
 
class SSHConnection(object):
  def __init__(self, host='192.168.12.68', port=22, username='locojoy',pwd='123321QQ!'):
    self.host = host
    self.port = port
    self.username = username
    self.pwd = pwd
    self.__k = None
 
  def run(self):
    self.connect() # 连接远程服务器
    self.upload('db.py','/tmp/1.py') # 将本地的db.py文件上传到远端服务器的/tmp/目录下并改名为1.py
    self.cmd('df') # 执行df 命令
    self.close()  # 关闭连接
 
  def connect(self):
    transport = paramiko.Transport((self.host, self.port))
    transport.connect(username=self.username, password=self.pwd)
    self.__transport = transport
 
  def close(self):
    self.__transport.close()
  def upload(self,local_path,target_path):
    sftp = paramiko.SFTPClient.from_transport(self.__transport)
    sftp.put(local_path,target_path)
 
  def cmd(self, command):
    ssh = paramiko.SSHClient()
    ssh._transport = self.__transport
    # 执行命令
    stdin, stdout, stderr = ssh.exec_command(command)
    # 获取命令结果
    result = stdout.read()
    print(result)
    return result
 
obj = SSHConnection()
obj.run()

The above is the detailed content of Learning sharing about paramiko module in python. 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