Python で ssh 接続をする方法です。
ssh_exec.py
#! /usr/bin/python
#
# ssh_exec.py
#
# Jan/20/2022
# ------------------------------------------------------------------
import os
import sys
import paramiko
from dotenv import load_dotenv
# ------------------------------------------------------------------
dotenv_path = '.env'
load_dotenv(dotenv_path)
HOST = os.environ.get("HOST")
USER = os.environ.get("USER")
COMMAND = os.environ.get("COMMAND")
#
sys.stderr.write("*** start ***\n")
client = paramiko.SSHClient()
client.load_system_host_keys()
try:
client.connect(HOST, username=USER, timeout=5.0)
#
stdin, stdout, stderr = client.exec_command(COMMAND)
str_out = ''
for line in stdout:
str_out += line
print(str_out)
client.close()
except Exception as ee:
sys.stderr.write(str(ee) + "\n")
#
del client, stdin, stdout, stderr
sys.stderr.write("*** end ***\n")
# ------------------------------------------------------------------
.env
HOST = "example.com"
USER = "scott"
COMMAND = "cd /home/scott/tmp/jan20 ; ls -l"
#スクリプトで実行する方法#
test.sh
cd /home/scott/tmp/jan20 ; ls -l
ssh scott@example.com < test.sh