文章内容
2023/6/28 6:48:45,作 者: 黄兵
Python paramiko 使用总结
现在使用 Python paramiko 登录服务器,需要实现如下功能:
获取当前的年月,如果存在年份目录,则判断是否存在月份目录,不存在月份目录,则新建月份目录,不存在年份目录,新建年份目录。
下面是 Python 的实现代码:
import paramiko
import datetime
# SSH连接信息
hostname = 'your_server_ip'
port = 22
username = 'your_username'
password = 'your_password'
# 创建SSH客户端
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# 连接服务器
client.connect(hostname, port, username, password)
# 获取当前的年月
now = datetime.datetime.now()
year = str(now.year)
month = str(now.month)
# 检查年份目录
stdin, stdout, stderr = client.exec_command('ls')
directories = stdout.read().decode().split()
if year not in directories:
# 年份目录不存在,创建年份目录
client.exec_command('mkdir ' + year)
print(f'Created year directory: {year}')
# 检查月份目录
stdin, stdout, stderr = client.exec_command(f'ls {year}')
subdirectories = stdout.read().decode().split()
if month not in subdirectories:
# 月份目录不存在,创建月份目录
client.exec_command(f'mkdir {year}/{month}')
print(f'Created month directory: {year}/{month}')
else:
print(f'Month directory already exists: {year}/{month}')
except paramiko.AuthenticationException:
print('Authentication failed. Please check your credentials.')
except paramiko.SSHException as ssh_exception:
print(f'Unable to establish SSH connection: {str(ssh_exception)}')
finally:
# 关闭SSH连接
client.close()在使用上面的代码时候,请确保将 your_server_ip,your_username 和 your_password 替换为实际的服务器IP地址、用户名和密码。
该代码首先使用Paramiko库创建一个SSH客户端,并使用提供的连接信息连接到服务器。然后,使用datetime模块获取当前的年月。接下来,通过执行远程命令ls获取服务器上的目录列表,并检查年份目录是否存在。
如果年份目录不存在,则使用mkdir命令创建年份目录。然后,再次执行远程命令ls检查月份目录是否存在。如果月份目录不存在,则使用mkdir命令创建月份目录。
最后,关闭SSH连接。
注意:在使用Paramiko连接到服务器之前,确保已安装Paramiko库,可以使用以下命令进行安装:pip install paramiko
其他相关推荐:
评论列表