Python 连接Linux服务器完成上传下载和执行命令及查询目录下的文件
记录一些用于连接linux获取远端文件或者上传文件的小工具,另外还有执行shell命令和查找linux目录下文件是否存在
# -*- coding: utf-8 -*-
"""
@Time : 2021/7/22 10:31
@Author : chenhj
@File : sshclient.py
@Software: PyCharm
@Comment :
"""
import osfrom stat
import S_ISDIR
import re
import paramikofrom paramiko.ssh_exception
import NoValidConnectionsError, AuthenticationException, SSHException
class SshRemoteConnection:
def __init__(self, hostname, port, user, password):
self.hostname = hostname
self.port = port
self.user = user
self.password = password
def do_connect(self, conn):
"""创建连接"""
if conn == "SSHClient":
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname=self.hostname,port=self.port,username=self.user,password=self.password)
print("正在连接 {}".format(self.hostname).center(100, '*'))
except NoValidConnectionsError as e:
print(f"连接失败:{
e}".center(100, '*'))
except AuthenticationException as e:
print(f"密码错误:{
e}".center(100, '*'))
return client
elif conn == "Transport":
# 获取Transport实例
tran = paramiko.Transport(self.hostname, int(self.port))
try:
# 连接SSH服务端
tran.connect(username=self.user, password=self.password)
except SSHException as e:
print(f'连接失败:{
e}'.center(100, '*'))
return tran
def