Coder Social home page Coder Social logo

amadeusitgroup / jumpssh Goto Github PK

View Code? Open in Web Editor NEW
78.0 10.0 28.0 174 KB

Python module to run commands on remote servers through one or more jump servers.

License: MIT License

Python 95.89% Shell 2.58% Dockerfile 1.53%
python ssh jumpbox jumpserver bastion-host proxycommand

jumpssh's Introduction

JumpSSH

image

image

image

image

image

image

JumpSSH

Python module to run commands on remote servers

Copyright

Copyright (c) 2017 Amadeus sas

License

MIT

Documentation

https://jumpssh.readthedocs.io

Development

https://github.com/AmadeusITGroup/JumpSSH

What

JumpSSH is a module for Python 2.7+/3.5+ that can be used to run commands on remote servers through a gateway.

It is based on paramiko library. It provides the ability to execute commands on hosts that are not directly accessible but only through one or more servers. Script does not need to be uploaded on a remote server and can be run locally.

Several authentication methods are supported (password, ssh key).

Commands can be run through several jump servers before reaching the remote server. No need to establish a session for each command, a single ssh session can run as many command as you want, including parallel queries, and you will get result for each command independently.

So, why another python library to setup remote server through ssh ? Here is a quick comparison with the most known existing python libraries
  • Paramiko: provide very good implementation of SSHv2 protocol in python but with a low level api a bit complex
  • Ansible: require more configuration and understanding to start. Moreover, support of bastion host is done with modification of local ssh config to use ProxyCommand, and this is needed for each bastion host.
  • Fabric: use of jump server is much easier than Ansible thanks to 'env.gateway' parameter, but does not allow jump through several servers.

Installation

To install JumpSSH, simply:

$ pip install jumpssh

Examples

establish ssh session with a remote host through a gateway:

>>> from jumpssh import SSHSession

# establish ssh connection between your local machine and the jump server
>>> gateway_session = SSHSession('gateway.example.com',
...                              'my_user', password='my_password').open()

# from jump server, establish connection with a remote server
>>> remote_session = gateway_session.get_remote_session('remote.example.com',
...                                                     password='my_password2')

run commands on remote host:

# command will be executed remotely and output will be returned locally and printed
>>> print(remote_session.get_cmd_output('ls -lta'))
total 28
drwxr-xr-x. 412 root    root    12288 Mar 21 14:25 ..
drwx------.   2 my_user my_user    28 Mar  6 19:25 .ssh
drwx------.   3 my_user my_user    70 Mar  6 19:25 .
-rw-r--r--.   1 my_user my_user    18 Jul 12  2016 .bash_logout
-rw-r--r--.   1 my_user my_user   193 Jul 12  2016 .bash_profile
-rw-r--r--.   1 my_user my_user   231 Jul 12  2016 .bashrc

# get exit code of the remotely executed command (here to check if a package is installed)
>>> remote_session.get_exit_code('yum list installed package_name')
0

remote rest api usage:

# calling rest api on remote host that is only accessible from the gateway
>>> from jumpssh import RestSshClient
>>> rest_client = RestSshClient(gateway_session)

# syntax is similar to requests library (http://docs.python-requests.org)
>>> http_response = rest_client.get('http://remote.example.com/helloworld')
>>> http_response.status_code
200
>>> http_response.text
u'Hello, World!'

remote files operations:

# check if remote path exists
>>> remote_session.exists('/path/to/a/file')
True

# copy file from local machine to remote host through gateway
>>> remote_session.put('/local/path/to/a/file', '/remote/path/to/the/file')

# create file on remote host from local content
>>> remote_session.file('/remote/path/to/the/file',
...                     content='remote file content', permissions='600')

# download remote file on local machine from remote host through gateway
>>> remote_session.get('/remote/path/to/the/file', '/local/path/')

Tests

jumpssh tests require docker, check docker documentation for how to install it depending on your OS. it also requires few python packages. To install them, run:

$ pip install -r requirements_dev.txt

To run the test suite, clone the repository and run:

$ pytest -sv tests/

or simply:

$ tox

Contributing

Bug Reports

Bug reports are hugely important! Before you raise one, though, please check through the GitHub issues, both open and closed, to confirm that the bug hasn't been reported before.

Feature Requests

If you think a feature is missing and could be useful in this module, feel free to raise a feature request through the GitHub issues

Code Contributions

When contributing code, please follow this project-agnostic contribution guide.

jumpssh's People

Contributors

fmaupas avatar pyup-bot avatar re-schneider avatar t-cas avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jumpssh's Issues

Feature request: get() from remote to gateway

Not sure if this is the place for feature requests, or if they're still being taken, but:

feature request to get files from remote to gateway, in addition to the current get from remote to local machine.

The close() function does not work as expected.

hi:

I have a cpe device, now I wish to execute reboot and then wait for it up.

my class is inherited from SSHSession of JumpSSH

    def wait_until_cpe_is_up(self, timeout=300, interval=10):
        for i in range(int(int(timeout) / interval)):
            try:
                self.logger.info('{} Try to reopen.'.format(self.name))
                self.open()
                self.logger.info('{} has up.'.format(self.name))
                return True
            except:
                self.logger.info('{} has not yet up.'.format(self.name))
                self.close()
                time.sleep(interval)
        return False

I have set the timeout of my class to 10, that means the open will be timeout=10.

I got the output like this:

[root@Server_130 lib_device]# python3 pet_cpe.py
20-08-25 10:30:21 [ INFO] CPE-860524031814682 ssh port: 10.108.183.134-2201, http_port: 8001, telnet_port: 2301
20-08-25 10:30:21 [ INFO] Exec Command: [reboot]
20-08-25 10:30:23 [ INFO] Exit code: 0, Command output: 
20-08-25 10:30:23 [ INFO] CPE-860524031814682 reboot done.
20-08-25 10:30:23 [ INFO] CPE-860524031814682 Try to reopen.
20-08-25 10:30:33 [ INFO] CPE-860524031814682 has not yet up.
20-08-25 10:30:43 [ INFO] CPE-860524031814682 Try to reopen.
20-08-25 10:30:53 [ INFO] CPE-860524031814682 has not yet up.
20-08-25 10:30:53 [ERROR] Exception: Error reading SSH protocol banner[Errno 9] Bad file descriptor
20-08-25 10:30:53 [ERROR] Traceback (most recent call last):
20-08-25 10:30:53 [ERROR]   File "/usr/local/lib/python3.6/site-packages/paramiko/transport.py", line 2211, in _check_banner
20-08-25 10:30:53 [ERROR]     buf = self.packetizer.readline(timeout)
20-08-25 10:30:53 [ERROR]   File "/usr/local/lib/python3.6/site-packages/paramiko/packet.py", line 380, in readline
20-08-25 10:30:53 [ERROR]     buf += self._read_timeout(timeout)
20-08-25 10:30:53 [ERROR]   File "/usr/local/lib/python3.6/site-packages/paramiko/packet.py", line 607, in _read_timeout
20-08-25 10:30:53 [ERROR]     x = self.__socket.recv(128)
20-08-25 10:30:53 [ERROR] OSError: [Errno 9] Bad file descriptor
20-08-25 10:30:53 [ERROR] 
20-08-25 10:30:53 [ERROR] During handling of the above exception, another exception occurred:
20-08-25 10:30:53 [ERROR] 
20-08-25 10:30:53 [ERROR] Traceback (most recent call last):
20-08-25 10:30:53 [ERROR]   File "/usr/local/lib/python3.6/site-packages/paramiko/transport.py", line 2039, in run
20-08-25 10:30:53 [ERROR]     self._check_banner()
20-08-25 10:30:53 [ERROR]   File "/usr/local/lib/python3.6/site-packages/paramiko/transport.py", line 2216, in _check_banner
20-08-25 10:30:53 [ERROR]     "Error reading SSH protocol banner" + str(e)
20-08-25 10:30:53 [ERROR] paramiko.ssh_exception.SSHException: Error reading SSH protocol banner[Errno 9] Bad file descriptor
20-08-25 10:30:53 [ERROR] 

20-08-25 10:31:03 [ INFO] CPE-860524031814682 Try to reopen.
20-08-25 10:31:13 [ INFO] CPE-860524031814682 has not yet up.
20-08-25 10:31:13 [ERROR] Exception: Error reading SSH protocol banner[Errno 9] Bad file descriptor
20-08-25 10:31:13 [ERROR] Traceback (most recent call last):
20-08-25 10:31:13 [ERROR]   File "/usr/local/lib/python3.6/site-packages/paramiko/transport.py", line 2211, in _check_banner
20-08-25 10:31:13 [ERROR]     buf = self.packetizer.readline(timeout)
20-08-25 10:31:13 [ERROR]   File "/usr/local/lib/python3.6/site-packages/paramiko/packet.py", line 380, in readline
20-08-25 10:31:13 [ERROR]     buf += self._read_timeout(timeout)
20-08-25 10:31:13 [ERROR]   File "/usr/local/lib/python3.6/site-packages/paramiko/packet.py", line 607, in _read_timeout
20-08-25 10:31:13 [ERROR]     x = self.__socket.recv(128)
20-08-25 10:31:13 [ERROR] OSError: [Errno 9] Bad file descriptor
20-08-25 10:31:13 [ERROR] 
20-08-25 10:31:13 [ERROR] During handling of the above exception, another exception occurred:
20-08-25 10:31:13 [ERROR] 
20-08-25 10:31:13 [ERROR] Traceback (most recent call last):
20-08-25 10:31:13 [ERROR]   File "/usr/local/lib/python3.6/site-packages/paramiko/transport.py", line 2039, in run
20-08-25 10:31:13 [ERROR]     self._check_banner()
20-08-25 10:31:13 [ERROR]   File "/usr/local/lib/python3.6/site-packages/paramiko/transport.py", line 2216, in _check_banner
20-08-25 10:31:13 [ERROR]     "Error reading SSH protocol banner" + str(e)
20-08-25 10:31:13 [ERROR] paramiko.ssh_exception.SSHException: Error reading SSH protocol banner[Errno 9] Bad file descriptor
20-08-25 10:31:13 [ERROR] 
20-08-25 10:31:23 [ INFO] CPE-860524031814682 Try to reopen.
20-08-25 10:31:33 [ INFO] CPE-860524031814682 has not yet up.
20-08-25 10:31:33 [ERROR] Exception: Error reading SSH protocol banner[Errno 9] Bad file descriptor
20-08-25 10:31:33 [ERROR] Traceback (most recent call last):
20-08-25 10:31:33 [ERROR]   File "/usr/local/lib/python3.6/site-packages/paramiko/transport.py", line 2211, in _check_banner
20-08-25 10:31:33 [ERROR]     buf = self.packetizer.readline(timeout)
20-08-25 10:31:33 [ERROR]   File "/usr/local/lib/python3.6/site-packages/paramiko/packet.py", line 380, in readline
20-08-25 10:31:33 [ERROR]     buf += self._read_timeout(timeout)
20-08-25 10:31:33 [ERROR]   File "/usr/local/lib/python3.6/site-packages/paramiko/packet.py", line 607, in _read_timeout
20-08-25 10:31:33 [ERROR]     x = self.__socket.recv(128)
20-08-25 10:31:33 [ERROR] OSError: [Errno 9] Bad file descriptor
20-08-25 10:31:33 [ERROR] 
20-08-25 10:31:33 [ERROR] During handling of the above exception, another exception occurred:
20-08-25 10:31:33 [ERROR] 
20-08-25 10:31:33 [ERROR] Traceback (most recent call last):
20-08-25 10:31:33 [ERROR]   File "/usr/local/lib/python3.6/site-packages/paramiko/transport.py", line 2039, in run
20-08-25 10:31:33 [ERROR]     self._check_banner()
20-08-25 10:31:33 [ERROR]   File "/usr/local/lib/python3.6/site-packages/paramiko/transport.py", line 2216, in _check_banner
20-08-25 10:31:33 [ERROR]     "Error reading SSH protocol banner" + str(e)
20-08-25 10:31:33 [ERROR] paramiko.ssh_exception.SSHException: Error reading SSH protocol banner[Errno 9] Bad file descriptor
20-08-25 10:31:33 [ERROR] 
20-08-25 10:31:43 [ INFO] CPE-860524031814682 Try to reopen.
20-08-25 10:31:53 [ INFO] CPE-860524031814682 has not yet up.
20-08-25 10:31:53 [ERROR] Exception: Error reading SSH protocol banner[Errno 9] Bad file descriptor
20-08-25 10:31:53 [ERROR] Traceback (most recent call last):
20-08-25 10:31:53 [ERROR]   File "/usr/local/lib/python3.6/site-packages/paramiko/transport.py", line 2211, in _check_banner
20-08-25 10:31:53 [ERROR]     buf = self.packetizer.readline(timeout)
20-08-25 10:31:53 [ERROR]   File "/usr/local/lib/python3.6/site-packages/paramiko/packet.py", line 380, in readline
20-08-25 10:31:53 [ERROR]     buf += self._read_timeout(timeout)
20-08-25 10:31:53 [ERROR]   File "/usr/local/lib/python3.6/site-packages/paramiko/packet.py", line 607, in _read_timeout
20-08-25 10:31:53 [ERROR]     x = self.__socket.recv(128)
20-08-25 10:31:53 [ERROR] OSError: [Errno 9] Bad file descriptor
20-08-25 10:31:53 [ERROR] 
20-08-25 10:31:53 [ERROR] During handling of the above exception, another exception occurred:
20-08-25 10:31:53 [ERROR] 
20-08-25 10:31:53 [ERROR] Traceback (most recent call last):
20-08-25 10:31:53 [ERROR]   File "/usr/local/lib/python3.6/site-packages/paramiko/transport.py", line 2039, in run
20-08-25 10:31:53 [ERROR]     self._check_banner()
20-08-25 10:31:53 [ERROR]   File "/usr/local/lib/python3.6/site-packages/paramiko/transport.py", line 2216, in _check_banner
20-08-25 10:31:53 [ERROR]     "Error reading SSH protocol banner" + str(e)
20-08-25 10:31:53 [ERROR] paramiko.ssh_exception.SSHException: Error reading SSH protocol banner[Errno 9] Bad file descriptor
20-08-25 10:31:53 [ERROR] 
20-08-25 10:32:03 [ INFO] CPE-860524031814682 Try to reopen.
20-08-25 10:32:09 [ INFO] CPE-860524031814682 has up.
[root@Server_130 lib_device]# 
[root@Server_130 lib_device]# 

Though at last the device is up, but I got so many error info.

I have tried to remove the close() like:

            except:
                self.logger.info('{} has not yet up.'.format(self.name))
                time.sleep(interval)

I got the output with no error, but in fact, the device is not up at all and the code has return:

[root@Server_130 lib_device]# python3 pet_cpe.py
20-08-25 10:33:55 [ INFO] CPE-860524031814682 ssh port: 10.108.183.134-2201, http_port: 8001, telnet_port: 2301
20-08-25 10:33:55 [ INFO] Exec Command: [reboot]
20-08-25 10:33:57 [ INFO] Exit code: 0, Command output: 
20-08-25 10:33:57 [ INFO] CPE-860524031814682 reboot done.
20-08-25 10:33:57 [ INFO] CPE-860524031814682 Try to reopen.
20-08-25 10:34:07 [ INFO] CPE-860524031814682 has not yet up.
20-08-25 10:34:17 [ INFO] CPE-860524031814682 Try to reopen.
20-08-25 10:34:17 [ INFO] CPE-860524031814682 has up.
[root@Server_130 lib_device]# 

only part of the command is executed on remote server

Hi Team,

I have the below issue where the complete command is not executed or the expected output is not returned - please can you let us know what is wrong and how to overcome this ?
I wont be able to use get_cmd_output function because I will have to pass the param username: (user used to execute the command) as well.

Two commands passed as list to run_cmd:

  1. source rc-core
  2. nova list --fields id,name,host,status | grep -w compute-1 | awk '{print $2}'

Expected output:
000b5774-105f-4569-8d71-9e5f4c49d2d6

Actual output:
DEBUG:root:output.output: | 000b5774-105f-4569-8d71-9e5f4c49d2d6 | 100-DEPLOYM_s2_0_b34c4ed9-742c-45f5-9eda-767120a9902e | compute-1.localdomain | ACTIVE |

debug logs:
DEBUG:paramiko.transport:userauth is OK
INFO:paramiko.transport:Authentication (password) successful!
INFO:jumpssh.session:Successfully connected to 'x.x.x.x:22'
DEBUG:jumpssh.session:Running command 'source rc-core && nova list --fields id,name,host,status | grep -w compute-1 | awk '{print $2}'' on 'x.x.x.x' as stack...
DEBUG:paramiko.transport:[chan 0] Max packet in: 32768 bytes
DEBUG:paramiko.transport:[chan 0] Max packet out: 32768 bytes
DEBUG:paramiko.transport:Secsh channel 0 opened.
DEBUG:paramiko.transport:[chan 0] Sesch channel 0 request ok
DEBUG:paramiko.transport:[chan 0] Sesch channel 0 request ok
DEBUG:paramiko.transport:[chan 0] EOF received (0)
DEBUG:paramiko.transport:[chan 0] EOF sent (0)
DEBUG:jumpssh.session:Closing connection to 'x.x.x.x:22'...
DEBUG:paramiko.transport:[chan 4] EOF sent (4)
DEBUG:paramiko.transport:EOF in transport thread
DEBUG:root:output.output: | 000b5774-105f-4569-8d71-9e5f4c49d2d6 | 100-DEPLOYM_s2_0_b34c4ed9-742c-45f5-9eda-767120a9902e | compute-1.localdomain | ACTIVE |
INFO:jumpssh.session:Connecting to 'x.x.x.x:22' through 'localhost' with user 'root'...
DEBUG:paramiko.transport:[chan 5] Max packet in: 32768 bytes
DEBUG:paramiko.transport:[chan 5] Max packet out: 32768 bytes

Also I have tried similar test using the below sample script on a different server, where I have created a file manually with the information that would return by the "nova list --fields id,name,host,status" command, filename: git.log
This test returns the expected output without any problem

import logging
from jumpssh import SSHSession
logging.basicConfig(filename="github_magics_debug_output.log", level=logging.DEBUG)

GATEWAY_SESSION = SSHSession('localhost', 'user1', password='pass1', port=40022).open()

REMOTE_SESSION = GATEWAY_SESSION.get_remote_session('x.x.x.x', 'user2', password='pass2')

OUTPUT = REMOTE_SESSION.run_cmd("cat git.log | grep -w compute-1 | awk '{print $2}'")

logging.debug("output.output: {}" .format(str(OUTPUT.output)))

print OUTPUT.output

output:
000b5774-105f-4569-8d71-9e5f4c49d2d6

Debug log:
DEBUG:paramiko.transport:userauth is OK
INFO:paramiko.transport:Authentication (password) successful!
INFO:jumpssh.session:Successfully connected to 'x.x.x.x:22'
DEBUG:jumpssh.session:Running command 'cat git.log | grep -w compute-1 | awk '{print $2}'' on 'x.x.x.x' as root...
DEBUG:paramiko.transport:[chan 0] Max packet in: 32768 bytes
DEBUG:paramiko.transport:[chan 0] Max packet out: 32768 bytes
DEBUG:paramiko.transport:Secsh channel 0 opened.
DEBUG:paramiko.transport:[chan 0] Sesch channel 0 request ok
DEBUG:paramiko.transport:[chan 0] Sesch channel 0 request ok
DEBUG:paramiko.transport:[chan 0] EOF received (0)
DEBUG:paramiko.transport:[chan 0] EOF sent (0)
DEBUG:root:output.output: 000b5774-105f-4569-8d71-9e5f4c49d2d6
DEBUG:paramiko.transport:EOF in transport thread
DEBUG:paramiko.transport:EOF in transport thread

Appreciate your support.

Could not run command in background

hi:
I need to start a process in background, so I run it like below:

from jumpssh import SSHSession
ssh_session = SSHSession('10.108.231.199', 'toor4nsn', password='oZPS0POrRieRtu').open()
ssh_session.run_cmd(cmd='ps -ef|grep tcpdump', silent=False, continuous_output=True)
ssh_session.run_cmd(cmd='nohup tcpdump -i br1 sctp  -w /tmp/local.pcap >/dev/null 2>/dev/null &', silent=False, continuous_output=True)
ssh_session.run_cmd(cmd='ps -ef|grep tcpdump', silent=False, continuous_output=True)

The output is:

[root@Server_130 lib_bts]# python3 ../try/a.py
root      2655  2646  0 10:47 pts/1    00:00:00 bash -c ps -ef|grep tcpdump
root      2657  2655  0 10:47 pts/1    00:00:00 grep tcpdump

root      2663  2646  0 10:47 pts/1    00:00:00 bash -c ps -ef|grep tcpdump
root      2665  2663  0 10:47 pts/1    00:00:00 grep tcpdump

Would you please help to check why?
Thanks.

Authentication Error

Hi
I am getting authentication error when ssh to Cisco router. Credentials are correct.
ssh to windows 10 machine works fine.

`omz@mac ~ % ssh [email protected] -p 8181
Password:

Welcome to the DevNet Sandbox for CSR1000v and IOS XE

The following programmability features are already enabled:

  • NETCONF
  • RESTCONF

Thanks for stopping by.

csr1000v-1#`

===========================

Using JumpSSH

`In [1]: from jumpssh import SSHSession

In [2]: jump_session = SSHSession('ios-xe-mgmt-latest.cisco.com', username='developer', port=8181, password='C1sco12345').open()

AuthenticationException Traceback (most recent call last)
/usr/local/lib/python3.6/site-packages/jumpssh/session.py in open(self, retry, retry_interval)
159 # connect to the host
--> 160 self.ssh_client.connect(**self.extra_parameters)
161

/usr/local/lib/python3.6/site-packages/paramiko/client.py in connect(self, hostname, port, username, password, pkey, key_filename, timeout, allow_agent, look_for_keys, compress, sock, gss_auth, gss_kex, gss_deleg_creds, gss_host, banner_timeout, auth_timeout, gss_trust_dns, passphrase, disabled_algorithms)
445 t.gss_host,
--> 446 passphrase,
447 )

/usr/local/lib/python3.6/site-packages/paramiko/client.py in _auth(self, username, password, pkey, key_filenames, allow_agent, look_for_keys, gss_auth, gss_kex, gss_deleg_creds, gss_host, passphrase)
763 if saved_exception is not None:
--> 764 raise saved_exception
765 raise SSHException("No authentication methods available")

/usr/local/lib/python3.6/site-packages/paramiko/client.py in _auth(self, username, password, pkey, key_filenames, allow_agent, look_for_keys, gss_auth, gss_kex, gss_deleg_creds, gss_host, passphrase)
750 try:
--> 751 self._transport.auth_password(username, password)
752 return

/usr/local/lib/python3.6/site-packages/paramiko/transport.py in auth_password(self, username, password, event, fallback)
1508 try:
-> 1509 return self.auth_handler.wait_for_response(my_event)
1510 except BadAuthenticationType as e:

/usr/local/lib/python3.6/site-packages/paramiko/auth_handler.py in wait_for_response(self, event)
235 e = AuthenticationException("Authentication failed.")
--> 236 raise e
237 if event.is_set():

AuthenticationException: Authentication failed.

The above exception was the direct cause of the following exception:

ConnectionError Traceback (most recent call last)
in
----> 1 jump_session = SSHSession('ios-xe-mgmt-latest.cisco.com', username='developer', port=8181, password='C1sco12345').open()

/usr/local/lib/python3.6/site-packages/jumpssh/session.py in open(self, retry, retry_interval)
172 else:
173 raise exception.ConnectionError("Unable to connect to '%s:%s' with user '%s'"
--> 174 % (self.host, self.port, self.username), original_exception=ex)
175
176 # Get the client's transport

ConnectionError: Unable to connect to 'ios-xe-mgmt-latest.cisco.com:8181' with user 'developer': Authentication failed.

In [3]:`

===========================

I can connect to the same box using Paramiko.

`In [10]: import paramiko

In [11]: ssh = paramiko.SSHClient()
...: ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
...: ssh.connect('ios-xe-mgmt-latest.cisco.com', port=8181, username='developer', password='C1sco12345', look_for_keys=False,allow_agent=False)
...: remote = ssh.invoke_shell()

In [12]: remote.send('sh run | i hostname\n')
Out[12]: 20

In [13]: output = remote.recv(65000)
...: print(output)
b'\r\nWelcome to the DevNet Sandbox for CSR1000v and IOS XE\r\n\r\nThe following programmability features are already enabled:\r\n - NETCONF\r\n - RESTCONF\r\n\r\nThanks for stopping by.\r\n\r\n\r\n\r\ncsr1000v-1#sh run | i hostname\r\nhostname csr1000v-1\r\ncsr1000v-1#'

In [14]:`

Private key file is encrypted

i have ed25519 private key, i need to use it to connect to jumpserver, but SSHSession init method does not seem to accept paramiko.Ed25519Key.from_private_key_file object, how to connect to jump server in this situation?

jumpssh 'get' fails if the remote file is binary. It is wrong to assume the files to get are text files

jump.SSHSession.get function uses the following codes to get a remote file and the write to a local file:
with open(local_path, mode='w') as local_file:
with sftp_client.file(copy_path) as remote_file:
local_file.write(remote_file.read().decode('utf-8'))
When the remote file is in binary format such as PCAP file, it fails at the decode('utf-8').
The following should work for binary file:
with open(local_path, mode='wb') as local_file:
with sftp_client.file(copy_path) as remote_file:
local_file.write(remote_file.read())
A file format argument may be added to distinguish the ascii/text from bin (binary) type.

gateway_session.get_remote_session not respecting 'timeout' parameter

When executing the command "gateway_session.get_remote_session" with a timeout set, if the address is not correct the timeout parameter will not be respected.
Example code:

gateway_session = SSHSession(
    gateway,
    gw_username,
    password=gw_password,
    timeout=5,
).open()  # This actually DOES respect timeout

session = gateway_session.get_remote_session(
    hostname,
    username,
    password=password,
    timeout=5,
)  # This does not respect timeout, for example if the hostname is wrong.

The issue seems to be in session.py in line 139:

ssh_channel = self.proxy_transport.open_channel("direct-tcpip", dest_addr, local_addr)

This tries to open a channel, but doesn't pass the timeout parameter, so it is not passed to the command (which does support it).

I think "timeout" is an important enough parameter to exist outside of kwargs, or at the very least observed and passed to open_channel.

jumpssh unable to read privatekey fils with passphrase

Although the Paramiko library accommodates for the use of passphrases on private key files in class paramiko.client.SSHClient.connect(), jumpssh seems to not have included this feature. Is it possible to request that to be added?
Regards

Unable to download file owned by root with SSHSession.get

When using SSHSession.get to download a file and that this remote file is owned by root, the temporary file created is also owned by root and so is not accessible from current user with paramiko.sftp_client.SFTPClient

`
jumpssh/session.py:627: in get
with sftp_client.file(copy_path) as remote_file:
/Library/Python/2.7/site-packages/paramiko/sftp_client.py:327: in open
t, msg = self._request(CMD_OPEN, filename, imode, attrblock)
/Library/Python/2.7/site-packages/paramiko/sftp_client.py:730: in _request
return self._read_response(num)
/Library/Python/2.7/site-packages/paramiko/sftp_client.py:781: in _read_response
self._convert_status(msg)


self = <paramiko.sftp_client.SFTPClient object at 0x10892f650>, msg = paramiko.Message('\x00\x00\x00\x01\x00\x00\x00\x03\x00\x00\x00\x11Permission denied\x00\x00\x00\x00')

def _convert_status(self, msg):
    """
        Raises EOFError or IOError on error status; otherwise does nothing.
        """
    code = msg.get_int()
    text = msg.get_text()
    if code == SFTP_OK:
        return
    elif code == SFTP_EOF:
        raise EOFError(text)
    elif code == SFTP_NO_SUCH_FILE:
        # clever idea from john a. meinel: map the error codes to errno
        raise IOError(errno.ENOENT, text)
    elif code == SFTP_PERMISSION_DENIED:
      raise IOError(errno.EACCES, text)

E IOError: [Errno 13] Permission denied

/Library/Python/2.7/site-packages/paramiko/sftp_client.py:809: IOError
`

How to execute multiple commands on remote host

Hi !!
Using library 'jumpssh'. I'd like to know how to get the output with different commands on remote session.

result = remote_session.run_cmd('show version | in Pro') print(result.output)
and for example, adding another command like 'show inter brief' on the same remote host.

I hope you can help me!

Thanks

Troublesome 'package.json' access at runtime in frozen applications

When using a Python frozen module (for example building an executable with PyInstaller), by default the builder only includes the Python bytecodes. So only that bytecodes are available when the module is imported at runtime.

But the JumpSSH package unconditionally reads the package.json file at runtime, just to get the package version.

For this reason JumpSSH can never be used as-is in a frozen Python executable. It requires to dive into the frozen applications builder and create specific hooks to include all JumpSSH files.

It would be a great help if the package simply specifies the version value in the code, so no data files are needed at runtime:
__version__ = "1.6.4"

Thanks in advance. And thanks for your good work.

Jumpssh Issue while establishing SSH with remote Alcatel Router

Hi,

Hope this discussion finds everyone well during this crisis.

I am using Jumpssh from RedHat server to Alcatel Router ( in the middle is Another RedHat server)

I have read all documents and i am following all the steps correctly but i am getting Error.

Here is the code!

from jumpssh import SSHSession

server_session = SSHSession('10.10.10.100', 'mohammed', password = 'python').open()

when i use print(server_session.get_cmd_output('ps aux | grep python'))

i am getting output

switch_session = server_session.get_remote_session('10.10.10.2', 'admin', password = 'python')

when i do print(switch_session.is_active()) i am getting True

print(switch_session.get_cmd_output('show port'))

i am getting Error when i use show port or any command

server_session.close()

and I am getting this Error

Traceback (most recent call last):

File "new.py", line 9, in

print(switch_session.get_cmd_output("show port"))

File "/usr/local/lib/python3.6/site-packages/jumpssh/session.py", line 419, in get_cmd_output

return self.run_cmd(cmd=cmd, **kwargs).output

File "/usr/local/lib/python3.6/site-packages/jumpssh/session.py", line 307, in run_cmd

channel.exec_command(my_cmd)

File "/usr/local/lib/python3.6/site-packages/paramiko/channel.py", line 72, in _check

return func(self, *args, **kwds)

File "/usr/local/lib/python3.6/site-packages/paramiko/channel.py", line 257, in exec_command

self._wait_for_event()

File "/usr/local/lib/python3.6/site-packages/paramiko/channel.py", line 1226, in _wait_for_event

raise e

File "/usr/local/lib/python3.6/site-packages/paramiko/transport.py", line 2055, in run

ptype, m = self.packetizer.read_message()

File "/usr/local/lib/python3.6/site-packages/paramiko/packet.py", line 459, in read_message

header = self.read_all(self.__block_size_in, check_rekey=True)

File "/usr/local/lib/python3.6/site-packages/paramiko/packet.py", line 303, in read_all

raise EOFError()

EOFError

I am looking for your help !

Thanks

Get remote session as another user

I have the following use case:

  • Access a central server via ssh
  • Change user to the one with permissions to ssh (via sudo su for example)
  • SSH to the other server.
    The user with permissions to ssh has all the keys. I could copy the keys to every individual user that can access the server, but I would prefer not doing so.
    Is there a way to use get_remote_session with another user? An easy way to run su or sudo su

Ignore error when run command

hi:
When I use run_cmd to list a directory, such as ls /tmp/PM*.xz, if no file exist, this will raise a exception and error_code=2;
But as you know, the file does not exist is a normal situation.
Some other command will raise some other error code, but what I want is to ignore these error.

Current I added a success_exit_code=[0, 1, 2], but is it possible to add a parameter like: ignore_error to the run_cmd ?

Thanks.

Problem when sending multiple commands via jumpSSH using multithreading

Hello,

I created a script where I send 15 000 commands to 70 switchs, so around 200 commands per switch. For each switch, I create one SSH connection via jumpSSH (via a jump server) this way:


# establish ssh connection between your local machine and the jump server
gateway_session = SSHSession('gateway.example.com',
                             'my_user', password='my_password').open()

# from jump server, establish connection with a remote server
remote_session = gateway_session.get_remote_session('remote.example.com',
                                                    password='my_password2')

Once the connection is established, I'm sending 200 commands using multithreading:

def main_loop():
   gateway_session = SSHSession('gateway.example.com',
                            'my_user', password='my_password').open()
   for switch in result.keys(): 
       remote_session = gateway_session.get_remote_session(switch["ip"],
                                                   password='my_password2')
       with ThreadPoolExecutor(max_workers=8) as executor:
           for command in result[switch]["commands"]:
               executor.submit(launch_command, command, remote_session)

def launch_command(command, remote_session):
   process = remote_session.get_cmd_output(command)           

The problem is that if I'm using 7 or 8 workers, it's not working properly (some information I get is missing) and I'm getting this error:

Secsh channel 55 open FAILED: open failed: Connect failed
Secsh channel 60 open FAILED: open failed: Connect failed
Secsh channel 113 open FAILED: open failed: Connect failed
Secsh channel 170 open FAILED: open failed: Connect failed
Secsh channel 213 open FAILED: open failed: Connect failed
Secsh channel 44 open FAILED: open failed: Connect failed...

If I'm using 6 workers or less, I have no any error and everything is working correctly.

I have the impression that it's creating more than one SSH connection per leaf and so that's why there is this error, because maybe I'm reaching the number max of sessions allowed in switches, but according to my code, only one connection per switch is set up.

Do you know why I'm experiencing this issue?
Thank you,

continuous_output=True prints bytes instead of strings in Python3

Example output:

DEBUG:jumpssh.session:Running command 'sudo yum install -y python36' on '192.168.39.110' as ec2-user...
b'Loaded plugins: priorities, update-motd, upgrade-helper\r\n'
b'Package python36-3.6.2-5.7.amzn1.x86_64 already installed and latest version\r\nNothing to do\r\n'

Feature request: recursive `put`

Hope it's OK to request a feature here, didn't see anything in the documentation about that.

Feature request is a recursive version of SSHSession.put for uploading an entire directory to the remote.

problem using jumpssh dosent upload right remote path, library to ssh a server throught a gateway

I'm coming here to ask you about jumpssh library if anybody had before the same problem,

So I tried to use the library in orther to connect to a server throught a gateway , and this is working fine , normally I'm connected ,

But when trying to execute some specific command the shell said that I need to install some tools , while they are already on the remote server . "xxx is not your PATH or not executable please install it".

And when showing the content of the remote path it dosent seem to show the same path as when I do directly in the server , I found this strange but certainly there is and explanation that I'm still ignoring .

Im supposing that the jumpssh library have some limits or specification that I ignore whenever I ve read the documentation : https://jumpssh.readthedocs.io/en/latest/api.html ( I followed this documentation to connect to my remote server throught the gateway.

else do you suggest another library for doing this ?

Anybody can suggest some tips ?

Thanks in advance.

how to use SU and password after creating a remote session

Hi team,
pleas help me to use su command with password using interactive password prompt in remote
session.

I have tried below approach. but not woring. please help.
gateway_session = SSHSession(hostname1, username1, password=password1).open()

remote_session = gateway_session.get_remote_session(hostname2, username=username2, password=password2)
remote_session.is_active()
remote_session.run_cmd('su')

Thanks in advance.

Accessing the remote session instance more than once throws Authentication Failure

I am trying to access a remote server through jump server and it throws below error if i use the instance second time. It works in first call. It happens with few servers.

from jumpssh import SSHSession
jump_server = SSHSession(','',password='').open()
remote_server = jump_server.get_remote_session(,'',password='')
print(remote_server.get_cmd_output('pwd'))<<WORKS
print(remote_server.get_cmd_output('pwd'))<<<<<<<<<<This throws below error

Failure: Authenticator could not validate SESS TOKEN <1k0xvdl5nxnv33chp4hj8yw0c71lwwu657at4q61lkvuvhh36vjr> of instance <1021216> status <59>

Add ability to select non-interactive shell

SUMMARY
At the current release, jumpssh exclusively creates interactive login shells (see man bash INVOCATION section).
It would be ideal if there was an option to make non-interactive non-login shells.

MOTIVATION
Our environment has an echo command in the .bashrc file. The output of that echo command is included in every string returned by run_cmd. We're going to work around this by capturing our desired output as a file and getting the file, but this isn't ideal.

ADDITIONAL INFORMATION
As a suggestion, I might implement this as arguments to run_cmd with the following signature:

  • interactive:bool=True specify that the command will be run in an interactive shell, defaults to True for backwards compatibility
  • login:bool=True specify that the command will be run in a login shell, default to True for backwards compatibility

Logic would need to be implemented and tested in session.py near line 282:

        my_cmd = cmd
        if username:
            user = username
            # need to run full command with shell to support shell builtins commands (source, ...)
            my_cmd = 'sudo su - %s -c "%s"' % (user, cmd.replace('"', '\\"')) #this replacement causes the user's command to be executed in an interactive login shell

how to connect through two or more getwayhost to the targethost and get the sshclient

self.client = SSHClient()
gate1_session = SSHSession(self.gate1host, jumpusername, password=jumppassword).open()
gate2_session = gate1_session.get_remote_session(self.gate2host, jumpusername, port=port, password=jumppassword)
Target_session = gate2_session.get_remote_session(self.hostname, self.username, password=password)
self.client = Target_session.ssh_client

I try like this but only get null object

"Error reading SSH protocol banner" occured when trying link a remote server through a jump server

Like the example on the webpage of pypi, code like this below:
`from jumpssh import SSHSession

establish ssh connection between your local machine and the jump server

gateway_session = SSHSession('gateway.example.com',
... 'my_user', password='my_password').open()

from jump server, establish connection with a remote server

remote_session = gateway_session.get_remote_session('remote.example.com',
... password='my_password2')`

SSH connection between my local machine and jump server is successful established.
But when trying to establish connection with the remote server, "Error reading SSH protocol banner" occured immediately.
This Traceback to paramiko.transport._check_banner.

JumpSSH Permission error

Hi,

I am have remote Linux Machine, Which asks password everyTime you do something on it. For Ex:
i'm using JumpSh Module to create a file. I have tried using use_sudo as True/False as well, When use_sudo =True its waiting for the password. But not sure how to pass them.

+++++++++++++++++++++++++++++++++++++++++++++++++++
gateway_session = SSHSession(controller_ip,args.user_name,port=port, password=pwd).open()
print("Hello")
print(gateway_session.file('/etc/resolv.conf', content='nameserver 10.220.220.228', permissions=777, use_sudo=True ))
+++++++++++++++++++++++++++++++++++++++++++++++++++++
gives back the below output
+++++++++++++++++++++

hello
None
Traceback (most recent call last):
File "C:/Users/503144060/PycharmProjects/python-ilorest-library-master/examples/Redfish/test.py", line 82, in
check()
File "C:/Users/503144060/PycharmProjects/python-ilorest-library-master/examples/Redfish/test.py", line 80, in check
print(gateway_session.file('/etc/resolv.conf', content='nameserver 10.220.220.228',permissions=777,use_sudo=False))
File "C:\Users\503144060\AppData\Roaming\Python\Python37\site-packages\jumpssh\session.py", line 699, in file
with sftp_client.file(copy_path, mode='w+') as remote_file:
File "C:\Users\503144060\AppData\Roaming\Python\Python37\site-packages\paramiko\sftp_client.py", line 372, in open
t, msg = self._request(CMD_OPEN, filename, imode, attrblock)
File "C:\Users\503144060\AppData\Roaming\Python\Python37\site-packages\paramiko\sftp_client.py", line 813, in _request
return self._read_response(num)
File "C:\Users\503144060\AppData\Roaming\Python\Python37\site-packages\paramiko\sftp_client.py", line 865, in _read_response
self._convert_status(msg)
File "C:\Users\503144060\AppData\Roaming\Python\Python37\site-packages\paramiko\sftp_client.py", line 896, in _convert_status
raise IOError(errno.EACCES, text)
PermissionError: [Errno 13] Permission denied

+++++++++++++++++++++

Gateway session can get garbage collected while remote session is still being accessed

When there are no longer any references the the gateway ssh session but there are to the remote session, the gateway session gets garbage collected too early, resulting in remote sessions failing with the following error:

paramiko.ssh_exception.SSHException: SSH session not active

Here's some code to re-create the issue:

import os
from jumpssh import SSHSession


def get_remote_session():
    user = os.getlogin()
    gateway_session = SSHSession(
        host="127.0.0.1",
        username=user,
    ).open()
    remote_session = gateway_session.get_remote_session(
        host="127.0.0.2",
        username=user,
    )
    return remote_session  # gateway ssh gets garbage collected here, which closes the gateway transport still needed by the remote session


if __name__ == "__main__":
    with get_remote_session() as remote_session:
        remote_session.get_sftp_client().get(
                    ".bashrc",
                    f"{os.path.expanduser('~')}\\Documents\\bashrc.txt"
                )

Which results in:

paramiko.ssh_exception.SSHException: SSH session not active

One possible fix which I've tested as working would be to add a reference to the gateway SSH session inside the jumpssh.SSHSession class. What do you think?

Output of Jump-ssh is not getting all receiving inputs from remote client

Hi,

As you can see below, when I run below command, I am not able to get response of the command which I sent ?
Do you have any idea?

server_session = SSHSession('xxxx','zzzz',password='yyyy')
switch_session = server_session.get_remote_session('aaa', 'xxx', password = 'xxxx')
channel = switch_session.ssh_transport.open_session()
channel.get_pty()
channel.invoke_shell()
channel.send('show port\n')
output = channel.recv(1024)
print(output)

Output of the script;
b'\r\n\r\nWelcome to ISAM\r\nlast login : 20/08/20 18:39:33\r\n'

Output of the command

Ports on NT

Port Admin Link Port Cfg Oper LAG/ Port Port Port
Id State State MTU MTU Bndl Mode Encp Type

nt:vp:1 Up Yes Up 1518 1518 - accs dotq vport
nt:mc:1 Up Yes Up 1518 1518 - accs dotq vport

=================================================================
Ports on NT-A

Port Admin Link Port Cfg Oper LAG/ Port Port Port
Id State State MTU MTU Bndl Mode Encp Type

want to ask : cannot jump to router with debug error : DEBUG:paramiko.transport:Rejecting "[email protected]" global request from server.

Hi all,

I want to ssh to router via jumphost.

  1. ssh from windows ssh terminal to jumphost (linux machine) : ok
  2. SSH from jumphost to router : ok
  3. using jumpssh + netmiko: nok. Error message:
    -->
    Traceback (most recent call last):
    File "C:\Program Files\Python311\Lib\site-packages\netmiko\base_connection.py", line 1138, in establish_connection
    self.remote_conn_pre.connect(**ssh_connect_params)
    File "C:\Program Files\Python311\Lib\site-packages\paramiko\client.py", line 386, in connect
    sock.connect(addr)
    TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
    <--

our code is taken from : https://python-forum.io/thread-26866.html
from netmiko import ConnectHandler
from jumpssh import SSHSession

targetnode = {
'device_type': 'alcatel_sros',
'ip': 'targed_node',
'username': 'admin',
'password': 'admin',
'port': 22,
}

jh_session = SSHSession('jumpserver_ip','jumpserver_user',password='jumpserver_passwd').open()
remote_connect = ConnectHandler(**targetnode)
output = remote_connect.send_command("show router interface")
print(output)

we modify ip and username and password.
But it cannot connect.

Enabling debug, we got :
...
INFO:paramiko.transport:Authentication (password) successful!
INFO:jumpssh.session:Successfully connected to 'jumphost:22'
DEBUG:paramiko.transport:Received global request "[email protected]"
DEBUG:paramiko.transport:Rejecting "[email protected]" global request from server.
DEBUG:paramiko.transport:EOF in transport thread
...

apparently it can connect to jumphost, but then got message : DEBUG:paramiko.transport:Rejecting "[email protected]" global request from server.

What should we do ?

thanks.

exception handling_connection error not working

Hi,

I am trying to SSH into number of device through loop but when any exception is occuring the code stops there without parsing any further.
Below is the code :
for ip in ips:
try:
net_connect = gateway_session.get_remote_session(ip,password=passw)
except ConnectionError as e:
continue
else:
output = net_connect.get_cmd_output('show running-config | i version')
ver = output.partition('\n')[0]
results = ip + "," + ver
to_doc_a(file_name, results)

Error

Secsh channel 1 open FAILED: Network is unreachable: Connect failed
Traceback (most recent call last):
ssh_channel = self.proxy_transport.open_channel("direct-tcpip", dest_addr, local_addr)
raise e
paramiko.ssh_exception.ChannelException: ChannelException(2, 'Connect failed')

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
net_connect = gateway_session.get_remote_session(ip,password=passw)
remote_session = SSHSession(host=host,
raise exception.ConnectionError("Unable to connect to '%s:%s' with user '%s'"
jumpssh.exception.ConnectionError: Unable to connect to '10.164.8.173:22' with user 'xxxxx': ChannelException(2, 'Connect failed')

remote_session.run_cmd("sudo -s") command stuck/waiting not processing for the next steps

I have this simple jumpssh code, Here I am trying to list down the available file on a remote server, which can be accessible to root user only.


from jumpssh import SSHSession

gateway_session = SSHSession('10.0.xx.xx', 'autouser', password='pwd123').open()

remote_session = gateway_session.get_remote_session('10.0.xx.yy', username="autouser", password='pwd123')
print("Exit code is:", remote_session.get_exit_code('ls'))

exit_code, output = remote_session.run_cmd("sudo -s")
print(exit_code)
print(output)

print(remote_session.get_cmd_output('ls -lrt'))

print("Closing connection")
remote_session.close()
gateway_session.close()

Output:

Exit code is: 0
Traceback (most recent call last):
File "D:/PycharmProjects/Python3/ssh/qcserver.py", line 19, in
exit_code, output = remote_session.run_cmd("sudo -s")
File "C:\Users\phitendra\AppData\Local\Programs\Python\Python38\lib\site-packages\jumpssh\session.py", line 387, in run_cmd
raise exception.RunCmdError(exit_code=exit_code,
jumpssh.exception.RunCmdError: Command (sudo -s) returned exit status (-1), expected [0]: [root@EMS autoinstall]#

Process finished with exit code 1

And my code waiting here for "sudo -s" execution, and after some time thrown error, while using the MobaXterm I am able to login to root using "sudo -s" command by just type and hit enter.

Is anything I am doing wrong here? plz get me the solution

Run a command with input data, got "paramiko.ssh_exception.AuthenticationException: Unable to connect to SSH agent"

Hi:
I use jumpssh to access my devices.
First, it is ok to execute some simple command on remote host, like:

cpe_session = SSHSession('10.108.183.134', 'root', port=2201, password='Si8a&2vV9').open()
lines = cpe_session.run_cmd(cmd=['ps|grep ssh|grep root@local'], silent=False, continuous_output=True)

All above code works fine.

Now I need to execute a command that may need to enter password, like:

command = 'ssh -N -f -L 0.0.0.0:2301:169.254.0.1:23 root@localhost'
lines = cpe_session.run_cmd(cmd=[command], silent=False, continuous_output=True,
input_data={'(y/n)':'y',
'password:': 'Si8a&2vV9'})

This time, I got error:

Exception in thread Thread-3:
Traceback (most recent call last):
File "/usr/lib64/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/usr/local/lib/python3.6/site-packages/paramiko/agent.py", line 122, in run
raise AuthenticationException("Unable to connect to SSH agent")
paramiko.ssh_exception.AuthenticationException: Unable to connect to SSH agent

I checked the code and comments the session.py, if I comment the line 302, like below, the error disappear.

#paramiko.agent.AgentRequestHandler(channel)

Would you please help to check this issue?

Thanks in advance.

Breaks becuase of hardcoding http1.0

Breaking for me when trying to hit remote endpoints that require http1.1 and I see http1.0 is hard coded here.

any workarounds?

curl -is --http1.0 -X GET "kube-state-metrics.test-internal.example.com"
HTTP/1.1 426 Upgrade Required
date: Tue, 27 Dec 2022 14:15:39 GMT
server: istio-envoy
connection: close
content-length: 0

AttributeError: 'NoneType' object has no attribute 'debug'

Hi friends,
I'm a beginner with programming, I hope someone can help me.
I installed python on windows 10.
(netmiko_project) C: \ Users \ GSPECIA \ netmiko_project \ Scripts> python --version
Python 3.8.2

I would like to connect to a router using a bridge machine and I am trying to use the jumpssh library, but something is not working:

from jumpssh import SSHSession
from getpass import getpass

password = getpass ()

gateway_session = SSHSession ("10.178.6.68", "user", password = password) .open ()
print (gateway_session)

remote_session = gateway_session.get_remote_session ("1.244.243.213", password = password)

If I try to launch the script, I get the following message:

(netmiko_project) C: \ Users \ GSPECIA \ netmiko_project \ Scripts> python jumphost.py
Password:
SSHSession (host = 10.178.6.68, username = gspecia, port = 22, private_key_file = None, proxy_transport = None)
Exception ignored in: <function SSHSession.del at 0x000001A362DC3AF0>
Traceback (most recent call last):
File "C: \ Users \ GSPECIA \ netmiko_project \ lib \ site-packages \ jumpssh \ session.py", line 89, in del
File "C: \ Users \ GSPECIA \ netmiko_project \ lib \ site-packages \ jumpssh \ session.py", line 196, in close
File "C: \ Users \ GSPECIA \ netmiko_project \ lib \ site-packages \ jumpssh \ session.py", line 198, in close
AttributeError: 'NoneType' object has no attribute 'debug'
Exception ignored in: <function SSHSession.del at 0x000001A362DC3AF0>
Traceback (most recent call last):
File "C: \ Users \ GSPECIA \ netmiko_project \ lib \ site-packages \ jumpssh \ session.py", line 89, in del
File "C: \ Users \ GSPECIA \ netmiko_project \ lib \ site-packages \ jumpssh \ session.py", line 198, in close
AttributeError: 'NoneType' object has no attribute 'debug'

(netmiko_project) C: \ Users \ GSPECIA \ netmiko_project \ Scripts>

What could be causing this problem?

If I connect normally through cmd everything works:

(netmiko_project) C: \ Users \ GSPECIA \ netmiko_project \ Scripts> ssh jumphost


Password:
Last login: Wed Apr 15 11:56:50 2020 from 10.133.207.1
Last login: Wed Apr 15 11:56:50 2020 from 10.133.207.1

Type xterm-256color unknown
$
ssh 1,244,243,213
[email protected]'s password:


User last login information:


Access Type: SSH


<8843RMCPE9>

Thanks in advance to all,
Girolamo

Can't execute background process on remote server

  • Python 3.9.1
  • jumpssh==1.6.5
  • paramiko==2.9.2

When I try to run a remote SSH command as a background process, it doesn't work. The command returns successfully, but the response is blank and it is as if the command was never run. When I run the same command with Paramiko, it works.

Here's a sample script that connects to the given ip and writes the date to a log file as a background process. If you run it, you'll see it works using Paramiko but no log file is created with JumpSSH.

import os
import paramiko
from jumpssh import SSHSession

HOST = '<server ip>'
USER = '<server username>'
ID_FILE = '<path to ssh key>'
CMD = 'date > {}.log &'


print("Using Paramiko\n=========================")
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

private_key = paramiko.RSAKey.from_private_key_file(os.path.expanduser(ID_FILE))
ssh_client.connect(hostname=HOST, username=USER, pkey=private_key)
stdin, stdout, stderr = ssh_client.exec_command(CMD.format('paramiko'))

out = stdout.read().decode().strip()
error = stderr.read().decode().strip()

ssh_client.close()
print("Out: {}\nError: {}".format(out, error))

print("\nUsing jumpssh\n=========================")
gateway_session = SSHSession(HOST, USER, private_key_file=os.path.expanduser(ID_FILE)).open()
output = gateway_session.get_cmd_output(CMD.format('jumpssh'))
print("Out: {}".format(output))

I modified session.py and commented out the get_pty() line at

channel.get_pty()

Once I did this the test script above started working, and the background process successfully created the log file:

-rw-rw-r-- 1 bhoover bhoover     29 Jan 13 12:19 paramiko.log
-rw-rw-r-- 1 bhoover bhoover     29 Jan 13 12:19 jumpssh.log

Any idea why this doesn't work with get_pty() included? The Paramiko docs look like they discourage its use when running a single command with exec_command, but I'm assuming it was included here for a reason.

Executing a long running command through Jumpssh

Hi,

Really appreciate your support on this.

I want to execute a command or a task however this command or task is different from Router to another Router. Some Router take 2 to 3 minutes and other around 5 minutes. i am using time.sleep(300) to overcome this but it is not sufficient or pythonic.

Is there something to add to make jumpssh code below to make it do the task.

from jumpssh import SSHSession
import paramiko
import time

server_session = SSHSession(hostname, username=username, password='password').open()

switch_session = server_session.get_remote_session(hostname, username=name, password=password)
channel = switch_session.ssh_transport.open_session()
channel.get_pty()
channel.invoke_shell()
channel.send("some long command\n")
time.sleep(300)
output = channel.recv(65535)
print(output)
server_session.close()
switch_session.close()

Sending hash fail

Hello,

I use this script to configure new users on remote linux boxes. I generate my password and sha512 hash locally and then send it via session.run_cmd :

Generated password :
mv!T09Z9vO!Cd3fSywZ+5koNUrtI5NXU!exsIw3_Pg@o17UxYIU?NHRjCMbxiOq!?u7aCiNhTfThuv?Y555R7ZdsL5IuB5ZpMp6y

Generated hash : $6$DCuUrE5U$dZkcgO10qlZVQeJRMrlWQSKG6forTa2qSKfLfSs.9ok4ZuniayOXuHORm50NWHOhmMrQJkyEdEYQekguoJJ860

ssh = SSHSession(server, username=username, password=password, port=port)
cmd = "useradd -G %s -p %s -m -c 'User1 Account' -s /bin/bash -U %s" % (group, hash, user)
ssh.run_cmd("echo {} >> /tmp/a".format(h), username="root", timeout=10, retry=1, retry_interval=1)

Output :

# cat /tmp/a
.9ok4ZuniayOXuHORm50NWHOhmMrQJkyEdEYQekguoJJ860

If you want to test :

def pw_gen(size):
    chars = string.ascii_letters + string.digits + string.punctuation
    return ''.join(random.choice(chars) for _ in range(size))
def sha512_crypt(password, salt=None, rounds=None):
    if salt is None:
        rand = random.SystemRandom()
        salt = ''.join([rand.choice(string.ascii_letters + string.digits)
                        for _ in range(8)])

    prefix = '$6$'
    if rounds is not None:
        rounds = max(1000, min(999999999, rounds or 5000))
        prefix += 'rounds={0}$'.format(rounds)

    return crypt.crypt(password, prefix + salt)

Thanks for your help !

cannot upload file to remote server

I am creating a scripts which to upload some files to remote server by a gateway server as below codes and met some errors, not sure if some things are missed, thanks.

gateway_session = SSHSession(gateway_ip, gateway_username, password=gateway_password).open()

remote_session = gateway_session.get_remote_session(remote_host_ip, remote_host_username, password=remote_host_password)

remote_session.put('/path/to/local_file', '/path/to/remote_file')

Error Message:

Traceback (most recent call last):
File "/usr/local/python3.7/lib/python3.7/site-packages/paramiko/sftp_client.py", line 130, in init
server_version = self._send_version()
File "/usr/local/python3.7/lib/python3.7/site-packages/paramiko/sftp.py", line 134, in _send_version
t, data = self._read_packet()
File "/usr/local/python3.7/lib/python3.7/site-packages/paramiko/sftp.py", line 201, in _read_packet
x = self._read_all(4)
File "/usr/local/python3.7/lib/python3.7/site-packages/paramiko/sftp.py", line 188, in _read_all
raise EOFError()
EOFError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "test.py", line 26, in
print(remote_session.put('/fa/autoFa/fail_info', '/home/fail_info'))
File "/usr/local/python3.7/lib/python3.7/site-packages/jumpssh/session.py", line 618, in put
use_sudo=use_sudo, owner=owner, permissions=permissions, username=username, silent=True)
File "/usr/local/python3.7/lib/python3.7/site-packages/jumpssh/session.py", line 706, in file
sftp_client = self.get_sftp_client()
File "/usr/local/python3.7/lib/python3.7/site-packages/jumpssh/session.py", line 551, in get_sftp_client
return paramiko.sftp_client.SFTPClient.from_transport(self.ssh_transport)
File "/usr/local/python3.7/lib/python3.7/site-packages/paramiko/sftp_client.py", line 170, in from_transport
return cls(chan)
File "/usr/local/python3.7/lib/python3.7/site-packages/paramiko/sftp_client.py", line 132, in init
raise SSHException("EOF during negotiation")
paramiko.ssh_exception.SSHException: EOF during negotiation

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.