Home >Backend Development >Python Tutorial >Introduction to python's paramiko module

Introduction to python's paramiko module

高洛峰
高洛峰Original
2017-03-26 18:43:172558browse

Paramiko is a module written in python language. It follows the SSH2 protocol and supports connection to remote servers through encryption and authentication.

Since it uses a cross-platform language like python, paramiko can support all platforms supported by python, such as Linux, Solaris, BSD, MacOS X, Windows, etc. Therefore, if you need to use When SSH is used to connect from one platform to another and perform a series of operations, paramiko is one of the best tools.

1. Install paramiko module

[root@yaoliang ~]# pip install paramiko

2. Remote connection

1. Method one

import paramiko
 
ssh = paramiko.SSHClient()                      # 创建客户端连接服务端的对象
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 允许连接不在know_hosts文件中的主机
ssh.connect(ip,port,username,password)          # 连接远程服务器

2. Method two

import paramiko
 
tus = (ip, port)
t = paramiko.Transport(tus)                     # 创建传输对象
t.connect(username=self.username, password=self.password)

3. File transfer

tus = (ip, port)
t = paramiko.Transport(tus)
t.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(t)    # 创建下载传输对象
sftp.get(localpath, remotepath)                 # 下载
sftp.put(localpath, remotepath)                 # 上传
t.close()

4. Example

import paramiko
from switch import switch_ip, switch_pwd, switch_username
from lib.read_ini import config
from lib.logsys import LogSys
import threading
import time
 
class UpDate(object):
 
    def __init__(self, dev, pname):
        self.cf = config()
        self.log = LogSys()                   
        self.pname = pname
        self.ip = switch_ip(dev)              # 根据dev获取远程服务器ip
        self.username = switch_username(dev)  # 获取用户名
        self.password = switch_pwd(dev)       # 获取密码
        self.port = int(self.cf.getvalue('server_conf', 'port'))
        self.localpath = self.cf.getvalue('write_path', 'upfilepath') + self.pname + ".zip"
        self.remotepath = self.cf.getvalue('write_path', 'topath') + self.pname + ".zip"
 
    def __trans_file(self):                   # 文件传输
        try:
            tus = (self.ip, self.port)
            t = paramiko.Transport(tus)       # 创建传输对象
            t.connect(username=self.username, password=self.password)  # 连接远程服务器
            sftp = paramiko.SFTPClient.from_transport(t)  # 创建下载传输对象
            sftp.put(self.localpath, self.remotepath)     # 上传文件
            t.close()
            print "trans_ok"
            return 5
        except Exception, e:
            print "put_file:" + str(e)
            return 0
 
    def __excuteup(self):                     # 远程操作
        ssh = paramiko.SSHClient()
        comm = '/root/test.sh ' + self.pname
        try:
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(self.ip,self.port,self.username,self.password,timeout=10) # 连接远程服务器
            stdin, stdout, stderr = ssh.exec_command(comm)  # 执行远程服务器上的脚本
            out = stdout.readlines()
            ssh.close()
            return 5
        except Exception, e:
            errmsg =  "excuteup Error.__excute" + str(e)
            ssh.close()
            self.log.writelog(errmsg)         # 将错误信息保存到日志
            return 0
 
    def runup(self):                          # 执行上传和远程执行命令的操作
        if self.__trans_file():
            if self.__excuteup():
                print "update success."
                return 5
            else:
                print "trans OK. excute ERR!"
                return 1
        else:
            return 1

The above is the detailed content of Introduction to python's paramiko module. 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