哈喽,大家好,我是木头左!

前言:为何选择Paramiko?

在网络运维和自动化领域,SSH(Secure Shell)协议是连接和管理远程服务器的常用手段。而Paramiko是一个用于进行SSH2会话的Python库,它支持加密、认证和文件传输等功能。使用Paramiko,可以方便地实现远程命令执行、文件上传下载等操作。

准备工作:安装与导入

确保你已经安装了paramiko库。如果没有安装,可以通过pip轻松完成:

pip install paramiko

安装完成后,在Python脚本中导入所需的模块:

import paramiko

创建SSH客户端

在开始任何操作之前,需要创建一个SSH客户端实例,并配置相关参数。

ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())  # 自动添加主机密钥

连接到远程服务器

接下来,使用你的服务器的IP地址、端口号、用户名和密码来连接到远程服务器。

ssh_client.connect(hostname='your_server_ip', port=22, username='your_username', password='your_password')

创建文件目录

一旦连接成功,你就可以通过执行SSH命令来创建文件目录了。以下是一个简单的示例,展示如何创建一个名为my_directory的新目录。

command = "mkdir my_directory"
stdin, stdout, stderr = ssh_client.exec_command(command)
print("Directory created:", stdout.read().decode())

上传文件

使用SFTP客户端

Paramiko提供了一个SFTP客户端,可以很方便地进行文件传输。你需要启动一个SFTP会话。

sftp_client = ssh_client.open_sftp()

然后,你可以使用put方法将本地文件上传到远程服务器。

    
def ftp():
    ssh = get_ssh(hostname, port, username, password)
    sftp = ssh.open_sftp()
    try:
        remote_file = sftp.open(remote_path, 'r')
    except Exception:
        print("remote file not exist: %s" % remote_path)        
        return
    file_util.write(local_path, remote_file.read().decode('utf-8'))
    remote_file.close()
    sftp.close()
    ssh.close()
    print('ftp %s 下载成功 \nfrom %s \nto %s' % (hostname, remote_path, local_path))
def up():
    ssh = get_ssh(hostname, port, username, password)
    try:
        stdin, stdout, stderr = ssh.exec_command('mkdir -p  {}'.format(remote_path))
        ssh.close()
        ssh = get_ssh(hostname, port, username, password)
        sftp = ssh.open_sftp()
        sftp.put(local_path+'\\'+file_name, remote_path+'/'+file_name)
    except Exception as e:
        print("remote file not exist: %s, Exception:%s" % (remote_path, str(e)))
        return
    sftp.close()
    ssh.close()
    print('ftp %s 上传成功 \nfrom %s \nto %s' % (hostname, local_path, remote_path))

处理异常

在实际操作过程中,可能会遇到各种异常,比如文件不存在、权限问题等。因此,合理地处理异常是非常重要的。

try:
    sftp_client.put(local_file_path, remote_directory)
except FileNotFoundError:
    print("Local file not found!")
except PermissionError:
    print("No permission to upload the file!")
except Exception as e:
    print("An error occurred:", str(e))
finally:
    sftp_client.close()
    ssh_client.close()

高级用法:断点续传与错误重试

在某些场景下,网络不稳定或者文件较大时,断点续传和错误重试功能就显得尤为重要。你可以通过设置put方法的resumable参数为True来实现断点续传,并通过循环和异常处理来实现错误重试。

结语:让自动化更加高效

通过本文的指导,你现在应该能够使用Python的Paramiko库来创建远程文件目录并上传文件。这些技能不仅能够提高你的工作效率,还能够让你在自动化运维的道路上更进一步。记得在实际操作中多加练习,以便更好地掌握这些有用的工具。

注意:上述代码仅为示例,实际使用时请根据你的环境和需求进行相应的调整。此外,敏感信息如服务器地址、用户名和密码应妥善保管,不应在公开场合泄露。

我是木头左,感谢各位童鞋的点赞、收藏,我们下期更精彩!