0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Python3: Paramiko の使い方 (ssh 接続)

Posted at

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
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?