У меня есть 3 Manux Machines (Hosta, Hostb, Hostc) , от hosta Я остановлюсь в входе в hostb через SSH и передавайте какой -то файл/каталог из Hosta на hostb . После того, как передача выполнена из Hosta на hostb , я хотел бы войти в систему и перевести те же файлы из hostb на hostc . Hosta может общаться только с hostb , и только hostb может общаться с hostc . Я пытаюсь добиться этого, используя приведенный ниже код Python, но я не получаю, как сделать SSH вход из Hostb на hostc , а также передавать файл/каталог, переданный из ((hostA to hostb ) для hostc .
main.py
import os
import paramiko
def main():
try:
ssh_client_b = connect_to_host("100.100.100.100", "hostB", "hostB123")
execute_command_over_ssh(ssh_client_b,
"uname")
execute_command_over_ssh(ssh_client,
"ls /home/hostB/")
transfer_file_or_directory(ssh_client_b,
"/home/hostA/repos/repo1/",
"/home/hostB/repos/")
# hostC is network reachable only from hostB
# below is where I'm stuck where I need to login to remote host hostC via SSH from hostB
# and transfer the same file/directory transferred previously to hostB from hostA
# Also, I would like to know how to issue command to execute in hostC and get back the result of it
# ssh_client_c = connect_to_host("200.200.200.200", "hostC", "hostC123")
# execute_command_over_ssh(ssh_client_c,
# "uname")
# execute_command_over_ssh(ssh_client_c,
# "ls /home/hostC/")
# transfer_file_or_directory(ssh_client,
# "/home/hostB/repos/repo1/",
# "/home/hostC/repos/")
finally:
print("closing ssh client connection")
ssh_client_b.close()
# ssh_client_c.close()
def connect_to_host(host_name, user_name, password):
try:
# Create object of SSHClient and
# connecting to SSH
ssh_client = paramiko.SSHClient()
# Adding new host key to the local
# HostKeys object(in case of missing)
# AutoAddPolicy for missing host key to be set before connection setup.
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(host_name,
port = 22,
username = user_name,
password = password)
except:
ssh_client.close()
return ssh_client
def execute_command_over_ssh(ssh_client, command):
# below line command will actually
# execute in your remote machine
(stdin, stdout, stderr) = ssh_client.exec_command(command)
# redirecting all the output in cmd_output
# variable
cmd_output = stdout.read()
print('log printing: ', command, cmd_output)
def transfer_file_or_directory(ssh_client, local_path, remote_path):
sftp = ssh_client.open_sftp()
if os.path.isfile(local_path):
transfer_file(sftp, local_path, remote_path)
print("file transfer done")
elif os.path.isdir(local_path):
dir_name = os.path.basename(os.path.dirname(local_path))
mkdir(sftp, '%s/%s' % (remote_path, dir_name), ignore_existing=True)
transfer_directory(sftp, local_path, os.path.join(remote_path, dir_name))
print("directory transfer done")
else:
print("invalid localpath: {local_path}")
sftp.close()
def transfer_file(sftp, local_path, remote_path):
sftp.put(local_path, remote_path)
def transfer_directory(sftp, local_path, remote_path):
for item in os.listdir(local_path):
if os.path.isfile(os.path.join(local_path, item)):
sftp.put(os.path.join(local_path, item), '%s/%s' % (remote_path, item))
else:
mkdir(sftp, '%s/%s' % (remote_path, item), ignore_existing=True)
transfer_directory(sftp, os.path.join(local_path, item), '%s/%s' % (remote_path, item))
def mkdir(sftp, path, mode=511, ignore_existing=False):
''' Augments mkdir by adding an option to not fail if the folder exists '''
try:
sftp.mkdir(path, mode)
except IOError:
if ignore_existing:
pass
else:
raise
Подробнее здесь: https://stackoverflow.com/questions/797 ... ed-machine
Как сделать SSH -соединение с другой подключенной к SSH машины ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
VSCODE SSH -соединение с root пользователь отключает через 20 секунд и отключает SSH
Anonymous » » в форуме Linux - 0 Ответы
- 26 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Понимание шума на экранной клавиатуре при подключенной аппаратной клавиатуре
Anonymous » » в форуме IOS - 0 Ответы
- 94 Просмотры
-
Последнее сообщение Anonymous
-