Files

38 lines
1.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
# 通过 SFTP 上传文件到远端(参数: host port user local remote [local remote ...])
# 依赖环境变量 SSHPASS
import os, sys, paramiko
def main():
host = sys.argv[1]
port = int(sys.argv[2]) if len(sys.argv) > 2 else 22
user = sys.argv[3] if len(sys.argv) > 3 else "root"
pw = os.environ.get("SSHPASS")
if not pw:
sys.stderr.write("ERROR: 请先设置环境变量 SSHPASS\n")
sys.exit(1)
t = paramiko.Transport((host, port))
t.connect(username=user, password=pw)
sftp = paramiko.SFTPClient.from_transport(t)
args = sys.argv[4:]
for i in range(0, len(args), 2):
local, remote = args[i], args[i + 1]
cur = ""
for p in [p for p in os.path.dirname(remote).split("/") if p]:
cur += "/" + p
try:
sftp.stat(cur)
except IOError:
try:
sftp.mkdir(cur)
except IOError:
pass
sftp.put(local, remote)
print(f"PUT {local} -> {remote}")
t.close()
if __name__ == "__main__":
main()