Python ssh exec shell command

Как использовать Python для работы с SSH

В данной статье мы рассмотрим, как использовать Python для работы с SSH (Secure Shell) – протоколом, используемым для безопасного удаленного управления системами и передачи данных между компьютерами.

Использование библиотеки Paramiko

Для работы с SSH в Python одной из наиболее популярных библиотек является Paramiko. Для установки этой библиотеки используйте следующую команду:

Создание SSH-соединения

Для создания SSH-соединения с удаленным сервером используйте следующий код:

import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('example.com', username='your_username', password='your_password')

🔒 Обратите внимание, что использование пароля для аутентификации может быть небезопасным. Лучше использовать ключи SSH для аутентификации.

Выполнение команд на удаленном сервере

После установления SSH-соединения можно выполнить команды на удаленном сервере. Вот пример выполнения команды ls :

stdin, stdout, stderr = ssh.exec_command('ls') print(stdout.read().decode())

Закрытие SSH-соединения

После выполнения всех необходимых операций не забудьте закрыть SSH-соединение:

Читайте также:  Однопроходные алгоритмы подсчет сумма произведение питон

Использование библиотеки Fabric

Еще одной популярной библиотекой для работы с SSH является Fabric. Она предоставляет высокоуровневый интерфейс для работы с SSH и упрощает выполнение многих операций. Для установки Fabric используйте следующую команду:

Создание SSH-соединения и выполнение команд с использованием Fabric

Вот пример использования Fabric для создания SSH-соединения и выполнения команды ls на удаленном сервере:

from fabric import Connection with Connection('example.com', user='your_username', connect_kwargs=) as conn: result = conn.run('ls') print(result.stdout.strip())

📝 Fabric также поддерживает использование ключей SSH для аутентификации, что является более безопасным вариантом.

Закрытие SSH-соединения в Fabric

Когда вы используете Fabric с контекстным менеджером with , SSH-соединение автоматически закрывается при выходе из блока кода.

Заключение

Теперь вы знаете, как использовать Python для работы с SSH с помощью таких библиотек, как Paramiko и Fabric. Это позволит вам безопасно управлять удаленными системами и выполнять различные операции с использованием Python-скриптов. Удачного кодирования! 🐍

Источник

Работа с ssh в Python

Хочу рассказать про paramiko — модуль для работы с ssh в python.
С его помощью можно написать скрипт, который получит доступ к удаленному серверу (или многим) и что-то на нем сделает.

Кому интересно — прошу под кат.

Достаточно часто на работе требовалось выполнить очень однотипные действия на серверах клиентов. Действия пустяковые, наподобие «исправить строчку №12 в конфигурационном файле» или «заменить файл „version_017“ на „version_018“. Это было легко, пока серверов не накопилось *надцать штук. Также подобные задачи надоедали очень быстро, поэтому подобную работу старались поручить новичкам с формулировкой „для приобретения навыков работы с ssh“.

Поначалу самые простые задачи можно было решить стандартными средствами ssh — копированием файла и удаленным исполнением кода. Также пробовали использовать утилиту empty .

Я в то время как раз начинал учить python, решил посмотреть, что в нем есть для этих целей. Гугл услужливо подсказал про paramiko.

Paramiko (комбинация слов языка есперанто „параноик“ и „друг“ — »paranoja» + «amiko») — это модуль для python версии 2.3 и выше, который реализует ssh2 протокол для защищенного (с шифрованием и аутентификацией) соединения с удаленным компьютером. При подключении предоставляется высокоуровневое API для работы с ssh — создается обьект SSHClient. Для большего контроля можно передать сокет (или подобный обьект) классу Transport и работать с удаленным хостом в качестве сервера или клиента. Клиенту для аутентификации можно использовать пароль или приватный ключ и проверку ключа сервера.

Небольшой пример использования этого модуля. Комментарии будут ниже.

import paramiko host = '192.168.0.8' user = 'login' secret = 'password' port = 22 client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(hostname=host, username=user, password=secret, port=port) stdin, stdout, stderr = client.exec_command('ls -l') data = stdout.read() + stderr.read() client.close() 

Получить данные для доступа к удаленному серверу можно любым удобным способом — прописать напрямую в коде, вынести в конфиг, базу данных и т.д. Очевидно, что если хостов несколько, то для их обхода нужно делать цикл.

Основным классом для подключения и удаленной работы является SSHClient. Он предоставляет нам «сессию» с которой мы можем работать далее.

В строчке client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) мы добавляем ключ сервера в список известных хостов — файл .ssh/known_hosts. Если при соединении с сервером ключа в нем не найдено, то по умолчанию ключ «отбивается» и вызввается SSHException.

Для соединения с сервером используем client.connect(). Авторизироваться можно как по комбинации логин-пароль так и по ключам. При соединении можно задать хост, имя пользователя, пароль, порт, ключ, и прочие параметры.

Строка client.exec_command(‘ls -l’) — выполняет команду на удаленном сервере. Потоки ввода-вывода программы возврашщаются в файлообразные обьекты — stdin, stdout, stderr.

Возможно, я недоразобрался, но у меня не получилось получить права рута на уделенном сервере. Буду благодарен, если мне подскажут, как это сделать. Для выполнения действий с правами суперпользователя делал так:

stdin, stdout, stderr = ssh.exec_command('sudo -S rm *') stdin.write('password' + '\n') stdin.flush() 

UPD: meph1st0 в комментариях предложил для этих целей воспользоваться классом Channel

import paramiko client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(. ) channel = сlient.get_transport().open_session() channel.get_pty() channel.settimeout(5) channel.exec_command('sudo ls') channel.send(password+'\n') print channel.recv(1024) channel.close() client.close() 

Для передачи файлов по sftp можно использовать класс Transport. Для непосредственной передачи файлов используются команды put и get.

host = "example.com" port = 22 transport = paramiko.Transport((host, port)) transport.connect(username='login', password='password') sftp = paramiko.SFTPClient.from_transport(transport) remotepath = '/path/to/remote/file.py' localpath = '/path/to/local/file.py' sftp.get(remotepath, localpath) sftp.put(localpath, remotepath) sftp.close() transport.close() 

Вкратце всё. Сайт проекта и документация — http://www.lag.net/paramiko/

UPD. В комметариях подсказали, что есть ряд других библиотек инструментов, которые также можно использовать для работы по ssh решения подобных задач. Из перечисленного: fabric, chef, puppet, libbsh2 (pylibbsh2), exscript и net-ssh-telnet на руби. Всем комментаторам спасибо.

Источник

How To Execute Shell Commands Over SSH Using Python?

You are currently viewing How To Execute Shell Commands Over SSH Using Python?

The Analytics Club

A prevalent task when automating the boring stuff in Python is to run shell commands. If you are working with servers or virtual machines, you’d also need to run commands on a remote computer.

You can use the standard Python module and subprocesses to run shell scripts. It’s an easy way to execute commands. But on remote computers, you may need other techniques.

This post walks you through executing raw shell scripts using ssh. Then we’ll also discuss more Pythonic ways to run scripts on remote computers.

Grab your aromatic coffee (or tea) and get ready…!

Running SSH commands using the subprocess module.

The subprocess module needs no further installation. It’s a standard Python library. Hence, you can use the ssh command line utility inside your subprocess run method.

The following command will run the Linux shell and get the free memory information of a remote computer. When running this script, the system will ask you to type in your password.

Note that the subprocess run command takes a list of arguments, not a string. But you can also use iterable such as a tuple or a set in place of a list.

import subprocess subprocess.run(("ssh", "@", "free", "-m"))
total used free shared buff/cache available Mem: 1985 583 165 31 1235 1186 Swap: 0 0 0

Copy files from and to remote computers.

In the same way, we can use the subprocess module to copy files from and to remote computers. The following Python script is an example of copying local files to a remote location using SCP.

This script uses argparser to get remote and local file paths as command-line arguments.

import subprocess import argparse import pathlib parser = argparse.ArgumentParser() parser.add_argument("-l", "--local-path", required=True, type=pathlib.Path) parser.add_argument("-r", "--remote-path", required=True, type=pathlib.Path) args = parser.parse_args() # Copy the file to the remote path command = ["scp", args.local_path, f"@:args.remote_path>"] subprocess.run(command)
$ python copy_file.py -l sample.txt -r /home/ubuntu/ sample.txt 100% 58 0.1KB/s 00:00

Passwordless ssh in Python

You’d have noticed that the ssh utility keeps asking for passwords every time you try to run a command on the remote computer. You can avoid this in two ways.

One is to embed passwords in the command itself. If you intend to share your code with others, you can set up an environment variable instead of hardcoding.

The second option is to set up an ssh key and add it to the remote computer’s authorized keys.

Embedded password in the ssh command

Before using this option, here’s a warning. I don’t recommend using passwords in any shell command. That’s because shell history will store the command along with your passwords. Also, the password is exposed to other processes running on the computer.

We need to use the ssh pass utility with ssh to use passwords in the same command.

The shell command below will run on a remote computer without prompting for a password. You can replace the `free -m` with any valid Unix command.

sshpass -p YOURPASSWORD> ssh USERNAME>@HOST_NAME> free -m

In our Python code, we can do this little tweak to embed password shell commands.

import os import subprocess command = [ "sshpass", "-p",  os.environ["PASSWORD"], # Assuming the password is provided through an env variable. "ssh",  os.environ["USERNAME"] + "@" + os.environ["HOSTNAME"], "free -m", ] subprocess.run(command)

Key files are the most stable way to connect through ssh. We generate an ssh key in our local computer and let the remote computer know about it. Generating key files creates two of them. One of them is the public key. It has an extension, `pub`. This is the key you should share with the remote computer, not the private one (with no extension).

The following steps will create an ssh key in Linux systems and copy it to a remote server. If you’re using Windows or Mac, follow the respective instructions.

ssh-keygen # Follow the on-screen instructions. You can also press enter to accept the default values evan $(ssh-agent) ssh-add ~/.ssh/id_rsa ssh-copy-id -i ~/.ssh/id_rsa.pub USERNAME>@HOSTNAME>

You might have to enter your password once (and for all) to copy the ssh key to the server. But on all subsequent ssh commands, you don’t have to worry about passwords or security.

Edit the SSH Config file for convenient server communications.

In Linux systems, you can also create an ssh config file. In the config file, you can specify a name for the connection and other parameters. This way, you don’t even have to remember the hostname or the username.

If you also followed the key file convention, you don’t have to worry about passwords either.

SSH Config files live inside the .ssh folder of your home directory ( ~/.ssh/config ), and it has no file extension. The following is an example of the content for SSH Config files.

Host prod HostName 3.231.56.176 User ubuntu Host dev HostName 54.232.237.63 User ubuntu

Once you have the ssh config setup, you can run remote shell commands with just the hostname.

The methods we’ve discussed in this section aren’t largely impacted our Python script. Yet, the code is more clear and more secure now.

Thanks for the read, friend. It seems you and I have lots of common interests. Say Hi to me on LinkedIn, Twitter, and Medium.

Not a Medium member yet? Please use this link to become a member because I earn a commission for referring at no extra cost for you.

Thuwarakesh

A tech voyager, sailing through the data science seas for 11+ years, charting courses of knowledge to enlighten fellow travelers.

You Might Also Like

A Brief Guide To Manage Configurations Using TOML Files

A Brief Guide To Manage Configurations Using TOML Files

How to Speed up Python Data Pipelines up to 91X?

07/30/2022

How to Speed up Python Data Pipelines up to 91X?

How to Run SQL Queries on Pandas Data Frames?

07/18/2021

How to Run SQL Queries on Pandas Data Frames?

How do we work

Readers support The Analytics Club. We earn through display ads. Also, when you buy something we recommend, we may get an affiliate commission. But it never affects your price or what we pick.

Источник

Оцените статью