Python如何实现SSH远程连接与文件传输
作者:冰点契约丶 时间:2023-06-12 12:34:02
Python SSH远程连接与文件传输
from paramiko import (SSHClient, SFTPClient, AutoAddPolicy)
import argparse
class Args(argparse.ArgumentParser):
def __init__(self, help_info: str = "remote host login args"):
"""
使用 python xx.py -h 查看参数传递帮助
:param help_info:
"""
super(Args, self).__init__(description=help_info)
def __call__(self, *args, **kwargs):
"""
:param args:
:param kwargs:
:return: 返回参数对象,可通过 args.xxx 获取参数
"""
self.add_argument("--ip", help="remote host ip address")
self.add_argument("--username", help="SSH login username", default="")
self.add_argument("--password", help="SSH login password", default="")
self.add_argument("--port", help="remote host port", default=22)
return self.parse_args()
class SSH(object):
def __init__(self, ip_address: str, username: str, password: str, port: int = 22):
"""
:param ip_address:远程ip地址
:param username:用户名
:param password:密码
:param port:端口号,默认22
"""
self.ip = ip_address
self.username = username
self.password = password
self.port = port
self.__client = SSHClient()
def connect(self) -> None:
"""
打开连接
:return:None
"""
self.__client.set_missing_host_key_policy(AutoAddPolicy())
self.__client.connect(self.ip, self.port, self.username, self.password)
def execute(self, command: str) -> None:
"""
执行命令,stderr未启用
:param command: windows命令
:return: None
"""
std_in, stdout, stderr = self.__client.exec_command(command=command)
print(stdout.read().decode("utf-8"))
def upload_file(self, local_file_path: str, remote_file_path: str) -> None:
"""
打开sftp会话,用于将本地文件上传到远程设备
:param local_file_path: 本地文件绝对路径
:param remote_file_path: 远程文件路径:命名方式:path+filename
:return:
"""
sftp: SFTPClient = self.__client.open_sftp()
try:
sftp.put(localpath=local_file_path, remotepath=remote_file_path)
print(f"file:{local_file_path} upload success!")
except Exception as e:
print(f"upload file file,please check whether the file path is correct!\nerror massage:{e} ")
def download_file(self, remote_file_path: str, local_save_path) -> None:
"""
打开sftp会话,用于将远程设备文件拉取到本地
:param remote_file_path: 远程设备绝对路径
:param local_save_path: 本地文件保存路径 命名方式:file +filename 注意需要指定文件名,否则报错
:return:
"""
sftp: SFTPClient = self.__client.open_sftp()
try:
sftp.get(remotepath=remote_file_path, localpath=local_save_path)
print(f"file:{remote_file_path} download success!")
except Exception as e:
print(f"upload file file,please check whether the file path is correct!\nerror massage:{e} ")
def get_shell(self) -> None:
"""
获取shell
:return:
"""
while True:
command = input(f"{self.ip}@{self.username}$:")
if command.__eq__("quit"):
break
self.execute(command=command)
def __del__(self):
print("Disconnected!")
self.__client.close()
Python建立ssh连接并返回shell执行命令结果
调用paramiko模块
paramiko是一个用于做远程控制的模块,使用该模块可以对远程服务器进行命令或文件操作。
安装
使用pip可以直接安装
pip3 install paramiko #python3
代码
import os
import sys
import paramiko
# 创建SSH对象
ssh = paramiko.SSHClient()
# 把要连接的机器添加到known_hosts文件中
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 输入参数并进行判断
if len(sys.argv) == 4:
ip = sys.argv[1]
uname = sys.argv[2]
passwd = sys.argv[3]
else:
#若用户没有输入命令行参数,则提示用户
print("Invalid amount of arguments.")
print("example:python3 ssh.py <ip> <uname> <passwd>")
sys.exit()
# 连接服务器
# 用户名密码
ssh.connect(hostname=ip, port=22, username=uname, password=passwd)
#ssh.connect(hostname='xxx.xxx.xx.xx', port=22, username='xxx', password='xxx')
cmd = 'cd /;ls -l;ifconfig'
# cmd = 'ls -l;ifconfig' #多个命令用;隔开
stdin, stdout, stderr = ssh.exec_command(cmd)
result = stdout.read()
if not result:
result = stderr.read()
ssh.close()
print(result.decode())
关于linux中stdin, stdout, stderr三个参数的说明
在Linux下,当一个用户进程被创建的时候,系统会自动为该进程创建三个数据流,stdin, stdout 和 stderr
三个数据流默认是表现在用户终端上的
执行一个shell命令行时通常会自动打开三个标准文件:
标准输入文件(stdin),通常对应终端的键盘;
标准输出文件(stdout)和标准错误输出文件(stderr),这两个文件都对应终端的屏幕。
进程将从标准输入文件中得到输入数据,将正常输出数据输出到标准输出文件,而将错误信息送到标准错误文件中。
证书登录
import os
import sys
import time
import paramiko
# 创建SSH对象
ssh = paramiko.SSHClient()
pkey = paramiko.RSAKey.from_private_key_file('/**/**') #私钥证书路径
# 把要连接的机器添加到known_hosts文件中
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if len(sys.argv) == 3:
ip = sys.argv[1]
uname = sys.argv[2]
#passwd = sys.argv[3]
else:
#若用户没有输入命令行参数,则提示用户
print("Invalid amount of arguments.")
print("example:python3 ssh.py <ip> <uname> <passwd>")
sys.exit()
# 连接服务器
# 私钥证书登录
ssh.connect(hostname=ip, port=22, username=uname, pkey=pkey)
cmd = 'cd /;ls -l;ifconfig'
# cmd = 'ls -l;ifconfig' #多个命令用;隔开
stdin, stdout, stderr = ssh.exec_command(cmd)
time.sleep(5)#增加更多时间来处理命令
result = stdout.read()
if not result:
result = stderr.read()
ssh.close()
print(result.decode())
来源:https://blog.csdn.net/qq_52751442/article/details/121908302
标签:Python,SSH,远程连接,文件传输
0
投稿
猜你喜欢
python通过pillow识别动态验证码的示例代码
2023-08-27 02:29:21
用Python复现二战德军enigma密码机
2022-04-12 23:22:59
全面解析Bootstrap表单使用方法(表单按钮)
2024-05-10 14:08:49
详解MySQL 慢查询
2024-01-26 19:00:58
深入理解Python虚拟机中元组(tuple)的实现原理及源码
2022-07-12 14:14:21
oracle远程连接服务器数据库图文教程
2023-07-12 22:22:37
Python 如何反方向迭代一个序列
2022-12-07 09:44:19
MySQL数据库与表的最基本命令大盘点
2010-08-31 14:29:00
ORACLE常见错误代码的分析与解决(二)
2024-01-21 16:37:29
VS2019创建MFC程序的实现方法
2023-03-30 09:32:34
Win8下python3.5.1安装教程
2021-11-15 13:14:54
Python Log文件大小设置及备份的方法
2022-08-02 13:46:14
vue-router命名路由和编程式路由传参讲解
2024-05-02 17:03:39
Python socket模块方法实现详解
2021-02-12 20:52:39
将python文件打包exe独立运行程序方法详解
2021-07-03 02:26:41
Oracle与SQL Server数据库镜像对比
2009-03-25 14:27:00
python爬虫基本知识
2022-10-10 09:09:34
Python如何读取、写入CSV数据
2022-02-17 14:03:31
Python判断和循环语句的分析与应用
2021-09-28 02:46:59
cmd连接mysql的方法详解
2024-01-17 12:10:58