文章内容
2023/6/28 7:00:02,作 者: 黄兵
Python paramiko 判断服务器是否存在相关目录
需要通过Python 的 Paramiko 库登录到 Ubuntu 服务器实现如下功能:
检查远程目录是否存在,并在目录存在时保存文件、目录不存在时创建目录。
下面是示例代码:
import paramiko # SSH连接信息 hostname = 'your_server_ip' port = 22 username = 'your_username' password = 'your_password' # 远程目录路径和本地文件路径 remote_directory = '/path/to/remote/directory' local_file_path = '/path/to/local/file.txt' # 创建SSH客户端 client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: # 连接服务器 client.connect(hostname, port, username, password) # 检查远程目录是否存在 stdin, stdout, stderr = client.exec_command(f'test -d {remote_directory} && echo "Exists"') result = stdout.read().decode().strip() if result == 'Exists': # 目录存在,保存文件到远程目录 sftp = client.open_sftp() sftp.put(local_file_path, f'{remote_directory}/file.txt') sftp.close() print(f'Saved file to remote directory: {remote_directory}') else: # 目录不存在,创建远程目录 client.exec_command(f'mkdir -p {remote_directory}') print(f'Created remote directory: {remote_directory}') 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
,/path/to/remote/directory
和 /path/to/local/file.txt
替换为实际的服务器IP地址、用户名、密码、远程目录路径和本地文件路径。
该代码首先使用Paramiko库创建一个SSH客户端,并使用提供的连接信息连接到服务器。
然后,通过执行远程命令来检查远程目录是否存在。如果目录存在,代码会使用SFTP将本地文件上传到远程目录中。如果目录不存在,代码会使用mkdir -p
命令创建远程目录。
最后,关闭SSH连接。
注意:在使用 Paramiko 连接到服务器之前,确保已安装 Paramiko 库,可以使用以下命令进行安装:pip install paramiko
其它相关推荐:
评论列表