Skip to content

Instantly share code, notes, and snippets.

@XiGou
Created October 12, 2022 07:01
Show Gist options
  • Save XiGou/7bab9edf1138f26cb3e4b84d37bab5b7 to your computer and use it in GitHub Desktop.
Save XiGou/7bab9edf1138f26cb3e4b84d37bab5b7 to your computer and use it in GitHub Desktop.
we usually need to upload file automatically by shell script, using scp or rsync, some we don't want to config ssh-pubkey authentication, use this gist can avoid input password manually.
#! /bin/python3
# alternative for scp command
import logging
import paramiko
class SSHClient:
def __init__(self, host, user, psw) -> None:
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect(
host,
username=user,
password=psw,
port=22,
allow_agent=False,
look_for_keys=False,
)
def upload_file_to_dir(self, file, dir):
sftp = self.ssh.open_sftp()
sftp.put(file, dir)
sftp.close()
remode_dir = "/data/xxx"
host = "x.x.x.x"
user = "root"
psw = "password"
logging.basicConfig(level=logging.DEBUG)
ssh = SSHClient(host, user, psw)
local_filename = "xxx.py"
ssh.upload_file_to_dir(local_filename, f"{remode_dir}/{local_filename}")
@RushFTK
Copy link

RushFTK commented Oct 12, 2022

Is it necessary to set the port config as a parameter in SSHClient?

@XiGou
Copy link
Author

XiGou commented Oct 13, 2022

Is it necessary to set the port config as a parameter in SSHClient?

the default port is 22, you don't need to pass it in.

But I prefer

Explicit is better than implicit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment