linux

如何利用Linux SFTP进行自动化脚本编写

小樊
43
2025-04-14 01:59:58
栏目: 智能运维
Linux服务器限时活动,0元免费领! 查看>>

利用Linux SFTP进行自动化脚本编写可以通过多种方式实现,其中最常见的是使用sshpass工具结合expect脚本,或者直接使用支持SFTP的编程语言(如Python)编写脚本。以下是两种常见的方法:

方法一:使用sshpassexpect

  1. 安装sshpass

    sudo apt-get install sshpass  # Debian/Ubuntu
    sudo yum install sshpass      # CentOS/RHEL
    
  2. 编写expect脚本expect是一个用于自动化交互式应用程序的工具,比如SSH。

    创建一个名为sftp_auto.sh的文件,内容如下:

    #!/usr/bin/expect -f
    
    set timeout -1
    set host [lindex $argv 0]
    set user [lindex $argv 1]
    set password [lindex $argv 2]
    set remote_dir [lindex $argv 3]
    set local_dir [lindex $argv 4]
    
    spawn sftp $user@$host
    expect "password:"
    send "$password\r"
    expect "sftp>"
    send "cd $remote_dir\r"
    expect "sftp>"
    send "lcd $local_dir\r"
    expect "sftp>"
    send "mput *\r"
    expect "sftp>"
    send "bye\r"
    interact
    
  3. 赋予执行权限并运行脚本

    chmod +x sftp_auto.sh
    ./sftp_auto.sh your_host your_user your_password /remote/directory /local/directory
    

方法二:使用Python和paramiko

  1. 安装paramiko

    pip install paramiko
    
  2. 编写Python脚本: 创建一个名为sftp_auto.py的文件,内容如下:

    import paramiko
    from paramiko import SSHClient
    from scp import SCPClient
    
    def sftp_upload(host, port, username, password, remote_dir, local_dir):
        ssh = SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(host, port, username, password)
        sftp = ssh.open_sftp()
    
        for filename in os.listdir(local_dir):
            local_path = os.path.join(local_dir, filename)
            remote_path = os.path.join(remote_dir, filename)
            sftp.put(local_path, remote_path)
    
        sftp.close()
        ssh.close()
    
    if __name__ == "__main__":
        host = 'your_host'
        port = 22
        username = 'your_user'
        password = 'your_password'
        remote_dir = '/remote/directory'
        local_dir = '/local/directory'
    
        sftp_upload(host, port, username, password, remote_dir, local_dir)
    
  3. 运行Python脚本

    python sftp_auto.py
    

这两种方法都可以实现SFTP的自动化操作,选择哪种方法取决于你的具体需求和环境。expect脚本适用于简单的交互式任务,而Python脚本则更加灵活和强大,适合复杂的自动化任务。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

相关推荐:如何用Linux SFTP进行自动化脚本编写

0
看了该问题的人还看了