10
votes

I already know there are ssh modules for Python, that's not for what I'm looking for. What I want to have is an python script to do the following:

  1. > connect to an [ input by user ] SSH host
  2. > connect using the credentials [ provided by the user ]
  3. > run command on the SSH host [ telnet to [host - input by user ]
  4. > Select menu item in the telnet session

Thanks in advance,

Best regards,

7
I don't get it. You need to do SSH-related stuff in Python and you are not interested in SSH modules for Python? - tokland
@Tokland, I'm looking for an example script. Not for answers like, "Fabric is a Python library and command-line tool for streamlining the use of SSH" :) - Ilias

7 Answers

4
votes

now the popular solution is Fabric

2
votes

If you're actually looking for a module that lets you automate CLI interaction, there's pexpect

1
votes

There are many libraries to do that.

  1. Subprocess
  2. Pexpect
  3. Paramiko (Mostly used)
  4. Fabric
  5. Exscript

You can check their documentation for the implementation.

0
votes

You can use the vassal package, which is exactly designed for this.

All you need is to install vassal and do

from vassal.terminal import Terminal
shell = Terminal(["ssh username@host", "cd scripts", "python foo1.py", "python foo2.py"])
shell.run()

This will run the command once every second, and you can make it run faster to change sec=0.1.

0
votes

I will refer you to:

import spur

shell = spur.SshShell(hostname="localhost", username="bob", password="password1", missing_host_key=spur.ssh.MissingHostKey.accept)
result = shell.run(["echo", "-n", "hello"])
print(result.output) # prints hello
import paramiko

hostname = 'enter_host'
username = 'enter_user'
password = 'enter_pass'

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname, username=username, password=password)

stdin, stdout, stderr = client.exec_command('cd /enter/valid/path && ls -l')

for line in stdout:
    print(line.strip('\n'))

client.close()

output:

-rw-rw-r-- 1 username username 2712 Jan 22 14:49 file_1.ini
-rw-rw-r-- 1 username username 5928 Jan 22 14:50 file_2.log
-rw-rw-r-- 1 username username 1454 Jan 14 23:31 file_3.sql
-rw-rw-r-- 1 username username  337 Jan 14 23:31 file_4.py
drwxrwxr-x 3 username username 4096 Jan 14 23:33 folder_1
drwxrwxr-x 2 username username 4096 Jan 14 23:33 folder_2
-rw-rw-r-- 1 username username 2566 Jan 21 12:38 file_5.md
-rw-rw-r-- 1 username username   63 Jan 14 23:31 file_6.txt
drwxrwxr-x 4 username username 4096 Jan 14 23:31 folder_3
drwxrwxr-x 9 username username 4096 Jan 21 12:38 folder_4
  • No libraries required
import subprocess

subprocess.Popen("ssh {user}@{host} {cmd}".format(user=user, host=host, cmd='ls -l'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()