Python接口自动化-Paramiko
一、用处
通过python第三方库Paramiko,SSH连接远程服务器
学这个目的是做接口自动化测试,数据初始化操作
二、安装
pip install paramiko
三、代码封装
"""
@Time:
@Target:
@Author: dingkw
"""
import paramiko
hostname='192.168.220.124'
username='root'
password='chances2018'
port=22
local_path = "./1.sh"
target_path = "/data/test/dingkw/1.sh"
class SSHConnection(object):
# 初始化主机名称、ip、端口等信息
def __init__(self, hostname, username, password, port=22):
self.hostname = hostname
self.username = username
self.password = password
self.port = port
# 连接远程服务器
def connect(self):
self.ssh = paramiko.SSHClient()
# 允许将信任的主机自动加入到host_allow 列表,此方法必须放在connect方法的前面
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect(hostname=self.hostname, username=self.username, password=self.password, port=self.port)
# 关闭连接
def close(self):
self.ssh.close()
# 执行linux命令
# 多条命令,以;或&&连接
def cmd(self, command):
stdin, stdout, stderr = self.ssh.exec_command(command,get_pty=True)
result = stdout.read()
print(result)
# 上传文件到服务器/下载服务器文件到本地
'''
坑:路径一定要写全
比如上传本地d:\1.txt到服务器/root下
local_path:d:\1.txt
target_path:/root/1.txt
'''
#
def updown(self,method,local_path,target_path):
self.transport = paramiko.Transport(self.hostname,self.port)
self.transport.connect(username=self.username,password=self.password)
sftp = paramiko.SFTPClient.from_transport(self.transport)
if method == "put":
sftp.put(local_path,target_path)
elif method == "get":
sftp.get(target_path,local_path)
obj = SSHConnection(hostname,username,password,port)
obj.connect()
#obj.updown(put,local_path,target_path)
obj.updown(method="get",local_path=local_path,target_path=target_path)
obj.cmd("cd /data/test/dingkw;ls")
ob

浙公网安备 33010602011771号