#!usr/bin/python
# coding: utf-8
import paramiko
import json
remotedir='/tmp/log'
remotefile = 'bst_manager-2019-04-17-info.log'
hostname = '192.168.50.34'
port = 8022
username = 'root'
password ='*****'
command = """tail -n 30 /tmp/log/bst_manager-2019-04-17-info.log | grep 'other'"""
def ssh_remote():
""" 1、基于用户名和密码连接
"""
print ("基于用户名和密码连接")
# 创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不再know_host文件的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname, port, username, password)
# 执行命令
stdin, stdout, stderr = ssh.exec_command(command)
data = stdout.readline()
cloud_data = json.loads(data)['other']
with open("../test_data_dev/data.json", 'w+', 0) as f:
cloud_data = json.dumps(cloud_data, indent=4, separators=(',', ':'))
f.write(cloud_data)
ssh.close()
print ("1. over\n\n\n")
#
# def ssh_remote_moth2():
#
# """ 2、基于用户名和密码连接
# """
# print ("基于用户名和密码连接,使用SSHClient, 封装Transport")
# ssh = paramiko.SSHClient()
# transport = paramiko.Transport(sock=(hostname, port))
# # print transport
# transport.connect(username=username, password=password)
#
# ssh._transport = transport
# stdin, stdout, stderr = ssh.exec_command(command)
# data = json.loads(stdout.readline())["other"]
#
# with open("../test_data_dev/data.json", 'w+', 0) as f:
# cloud_data = json.dumps(data, indent=4, separators=(',', ':'))
# f.write(cloud_data)
# ssh.close()
#
# transport.close()
# print ('2. over \n\n\n')
#
#
# def down_device_file():
#
# transport = paramiko.Transport(('192.168.50.34', 8022))
# transport.connect(username='root', password='O3OwTr(01{@sVhDL')
#
# sftp = paramiko.SFTPClient.from_transport(transport)
# sftp.put('/tmp/location.txt', '/tmp/sensoro/server.txt')
#
# # 检查有无上传成功
# ssh = paramiko.SSHClient()
# ssh._transport = transport
# stdin, stdout, stderr = ssh.exec_command('ls -al /tmp/sensoro/')
# print(str(stdout.read(), encoding='utf-8'))
#
# # 将remove_path 下载到本地 local_path
# sftp.get('/root/conf/bst_conf.json', '/Users/linyue/mywork/server_file/bst_conf.json')
#
# transport.close()
# print("3. over")
转载于:https://www.cnblogs.com/lin-yue/p/10723528.html