How to run a program in Paramiko's SSH ProxyCommand - python

I'm pretty new with Paramiko and python in general. I'm trying to connect to a server and execute some commands on it by ssh through the use of Paramiko's API and a program called Pomerium. My ssh config file is as shown below
Host *.stg-id-proxy.lab.com
ProxyCommand pomerium-cli tcp --listen - %h:%p
User placeholder
and my python code in file "ssh4.py" is as follows
import paramiko
host = "place.stg-id-proxy.lab.com"
port = 22
username = "placeholder"
password = "pass#!#"
command = "pwd"
proxy = paramiko.ProxyCommand("pomerium-cli tcp --listen - %h:%p")
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, port, username, password, allow_agent=False, look_for_keys=False, sock=proxy, banner_timeout=60)
stdin, stdout, stderr = ssh.exec_command(command)
lines = stdout.readlines()
print(lines)
but when I tried running:
python3 ssh4.py
I keep getting the following error
Exception (client): Error reading SSH protocol banner
Traceback (most recent call last):
File "/Users/placeholder/Library/Python/3.8/lib/python/site-packages/paramiko/transport.py", line 2271, in _check_banner
buf = self.packetizer.readline(timeout)
File "/Users/placeholder/Library/Python/3.8/lib/python/site-packages/paramiko/packet.py", line 380, in readline
buf += self._read_timeout(timeout)
File "/Users/placeholder/Library/Python/3.8/lib/python/site-packages/paramiko/packet.py", line 622, in _read_timeout
raise socket.timeout()
socket.timeout
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/placeholder/Library/Python/3.8/lib/python/site-packages/paramiko/transport.py", line 2094, in run
self._check_banner()
File "/Users/placeholder/Library/Python/3.8/lib/python/site-packages/paramiko/transport.py", line 2275, in _check_banner
raise SSHException(
paramiko.ssh_exception.SSHException: Error reading SSH protocol banner
Traceback (most recent call last):
File "/Users/placeholder/Library/Python/3.8/lib/python/site-packages/paramiko/transport.py", line 2271, in _check_banner
buf = self.packetizer.readline(timeout)
File "/Users/placeholder/Library/Python/3.8/lib/python/site-packages/paramiko/packet.py", line 380, in readline
buf += self._read_timeout(timeout)
File "/Users/placeholder/Library/Python/3.8/lib/python/site-packages/paramiko/packet.py", line 622, in _read_timeout
raise socket.timeout()
socket.timeout
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "ssh4.py", line 11, in <module>
ssh.connect(host, port, username, password, allow_agent=False, look_for_keys=False, sock=proxy, banner_timeout=60)
File "/Users/placeholder/Library/Python/3.8/lib/python/site-packages/paramiko/client.py", line 406, in connect
t.start_client(timeout=timeout)
File "/Users/placeholder/Library/Python/3.8/lib/python/site-packages/paramiko/transport.py", line 699, in start_client
raise e
File "/Users/placeholder/Library/Python/3.8/lib/python/site-packages/paramiko/transport.py", line 2094, in run
self._check_banner()
File "/Users/placeholder/Library/Python/3.8/lib/python/site-packages/paramiko/transport.py", line 2275, in _check_banner
raise SSHException(
paramiko.ssh_exception.SSHException: Error reading SSH protocol banner
So, any help would be appreciated. Also documentation for Pomerium can be found here:
https://github.com/pomerium/cli
Thank you in advance.

Related

Having trouble logging in to IMAP account in Python3.61

I am developing a Python script in version 3.61 to connect to an Imap server and select all email messages older than a certain date. I imported the imapclient module and then provided the following in the IDLE shell:
HOST = 'imap.comcast.net'
USERNAME = 'username'
PASSWORD = 'topsecret'
ssl = False
server = IMAPClient(HOST, use_uid=True, ssl=ssl)
server.login(USERNAME, PASSWORD)
I received the following errors after using the login option:
Traceback (most recent call last):
File "C:\Python\Python36-32\lib\imaplib.py", line 1011, in _command_complete
typ, data = self._get_tagged_response(tag)
File "C:\Python\Python36-32\lib\imaplib.py", line 1123, in
_get_tagged_response
self._check_bye()
File "C:\Python36-32\lib\imaplib.py", line 926, in _check_bye
raise self.abort(bye[-1].decode(self._encoding, 'replace'))
imaplib.IMAP4.abort: Zimbra IMAP server terminating connection
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
server.login(USERNAME, PASSWORD)
File "C:\Python\Python36-32\lib\site-packages\imapclient\imapclient.py",
line
215, in login
unpack=True,
File "C:\Python\Python36-32\lib\site-packages\imapclient\imapclient.py",
line
1180, in _command_and_check
typ, data = meth(*args)
File "C:\Python36-32\lib\imaplib.py", line 588, in login
typ, dat = self._simple_command('LOGIN', user, self._quote(password))
File "C:\Python\Python36-32\lib\imaplib.py", line 1188, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "C:\Python\Python36-32\lib\imaplib.py", line 1013, in _command_complete
raise self.abort('command: %s => %s' % (name, val))
imaplib.IMAP4.abort: command: LOGIN => Zimbra IMAP server terminating
connection
The docs indicate to me that this should be sufficient to make the connection but it is not clear why the connection is terminated after attempting the login.
Any help provided would be most welcome.

Proxycommand in paramiko

I'm trying to do a simple proxycommand using paramiko in python.
Basically I'm trying to replicate the behaviour of this ssh command:
ssh -i ~/.ssh/destination_key user#destination.test.internal -o 'ProxyCommand ssh -i ~/.ssh/jumpbox_key -W %h:%p user#jumpbox.test.internal'
The above works as expected amd connects to destination.test.internal.
I'm trying to do the same thing in python with the following on the same box:
#!/usr/bin/python3
import paramiko
import argparse
addresses = ["destination.test.internal"];
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
proxy = paramiko.ProxyCommand("ssh -i ~/.ssh/jumpbox_key -W %h:%p user#jumpbox.test.internal")
for address in addresses:
#Connect over ssh to each server
try:
ssh.connect(address , username='user', key_filename="~/.ssh/destination_key", sock = proxy )
except paramiko.AuthenticationException:
print ("Authentication Failed")
except paramiko.SSHException:
print ("Connection Failed")
stdin,stdout,stderr = ssh.exec_command('ls -l')
print (stdout.readlines())
ssh.close()
Needless to say this isn't working. It's failing with:
Traceback (most recent call last):
Exception: Error reading SSH protocol banner
File "/usr/local/lib/python3.5/dist-packages/paramiko/transport.py", line 1893, in _check_banner
buf = self.packetizer.readline(timeout)
File "/usr/local/lib/python3.5/dist-packages/paramiko/packet.py", line 331, in readline
buf += self._read_timeout(timeout)
File "/usr/local/lib/python3.5/dist-packages/paramiko/packet.py", line 501, in _read_timeout
raise socket.timeout()
socket.timeout
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/paramiko/transport.py", line 1749, in run
self._check_banner()
File "/usr/local/lib/python3.5/dist-packages/paramiko/transport.py", line 1897, in _check_banner
raise SSHException('Error reading SSH protocol banner' + str(e))
paramiko.ssh_exception.SSHException: Error reading SSH protocol banner
Connection Failed
Traceback (most recent call last):
File "./log_file_fix.py", line 31, in <module>
stdin,stdout,stderr = ssh.exec_command('ls -l')
File "/usr/local/lib/python3.5/dist-packages/paramiko/client.py", line 436, in exec_command
chan = self._transport.open_session(timeout=timeout)
File "/usr/local/lib/python3.5/dist-packages/paramiko/transport.py", line 716, in open_session
timeout=timeout)
File "/usr/local/lib/python3.5/dist-packages/paramiko/transport.py", line 800, in open_channel
raise SSHException('SSH session not active')
paramiko.ssh_exception.SSHException: SSH session not active
However I'm not sure where I'm going wrong.
Instead of %h:%p, Specify host and port inside paramiko.ProxyCommand()
proxy = paramiko.ProxyCommand("ssh -i ~/.ssh/jumpbox_key -W DESTINATION_HOST_ADDRESS:22 user#jumpbox.test.internal")
You have to change your code like below:
#!/usr/bin/python3
import paramiko
import argparse
addresses = ["destination.test.internal"];
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
for address in addresses:
proxy_jump_command='ssh -i ~/.ssh/jumpbox_key -W {HOST}:{PORT} user#jumpbox.test.internal'.format(HOST=address, PORT=22)
proxy = paramiko.ProxyCommand(proxy_jump_command)
#Connect over ssh to each server
try:
ssh.connect(address , username='user', key_filename="~/.ssh/destination_key", sock = proxy )
except paramiko.AuthenticationException:
print ("Authentication Failed")
except paramiko.SSHException:
print ("Connection Failed")
stdin,stdout,stderr = ssh.exec_command('ls -l')
print (stdout.readlines())
ssh.close()

how to switch user and pass password using paramiko

I am using a Python script which requires to have root access.
First I am becoming a normal user, then I want to become root. But, stdin.write is still throwing error.
Here is my script:
import os
import paramiko
import subprocess
user="a554511"
p="xxxxxxx"
root="abcdefgh"
x="vljhggsajgfj"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(x,username=user,password=p)
stdin.write('su -')
stdin.write("\n")
stdin.write(root)
stdin.flush()
stdin,stdout,stderr=ssh.exec_command('pwd')
x=stdout.readlines()
print(x)
ssh.close()
The error I get is:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/site-packages/paramiko-1.15.2-py2.6.egg/paramiko/file.py", line 339, in write
self._write_all(data)
File "/usr/lib/python2.6/site-packages/paramiko-1.15.2-py2.6.egg/paramiko/file.py", line 456, in _write_all
count = self._write(data)
File "/usr/lib/python2.6/site-packages/paramiko-1.15.2-py2.6.egg/paramiko/channel.py", line 1220, in _write
self.channel.sendall(data)
File "/usr/lib/python2.6/site-packages/paramiko-1.15.2-py2.6.egg/paramiko/channel.py", line 744, in sendall
sent = self.send(s)
File "/usr/lib/python2.6/site-packages/paramiko-1.15.2-py2.6.egg/paramiko/channel.py", line 698, in send
return self._send(s, m)
File "/usr/lib/python2.6/site-packages/paramiko-1.15.2-py2.6.egg/paramiko/channel.py", line 1058, in _send
raise socket.error('Socket is closed')
socket.error: Socket is closed

Python FTP (from ftplib module) fails on login to SFTP server

I am doing the following
>> from ftplib import FTP
>> s = FTP('host','user','password') # Connect
and it fails giving the following
Traceback (most recent call last): File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ftplib.py", line 117, in __init__
self.connect(host)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ftplib.py", line 132, in connect
self.sock = socket.create_connection((self.host, self.port), self.timeout)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 571, in create_connection
raise err socket.error: [Errno 60] Operation timed out
I know that host, user, passwd are correct
How do I debug/fix this error?
WinSCP (which you've otherwise been using to connect to the same server) supports SFTP and SCP, not FTP.
To write a Python program using SFTP, you should be using the Paramiko library.
Try doing it like this:
try:
s = FTP(host)
s.login(user, password)
except Exception, e:
print "The error was:", str(e)

how to handle socket errors as exceptions in python + paramiko?

I want to return an error code when the following error gets raised:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "UserManagementRemote.py", line 202, in create_group
ssh.connect(hostname, username=user, password=remotepass)
File "/usr/lib/python2.6/site-packages/paramiko/client.py", line 290, in connect
sock.connect(addr)
File "<string>", line 1, in connect
socket.error: [Errno 113] No route to host
>>>
But I'm currently having trouble catching the error raised.
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname, username=user, password=remotepass)
except paramiko.AuthenticationException:
return 259
except socket.error:
return 261
chan = ssh.get_transport().open_session()
chan.exec_command(command)
codest = chan.recv_exit_status()
ssh.close()
return codest
Resulting on this:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "UserManagementRemote.py", line 207, in create_group
except socket.error:
NameError: global name 'socket' is not defined
>>>
Any ideas?
Do
import socket
in the module where you do the exception handling.
To prevent this problem in the future, run pyflakes on all your source files. That will catch a lot of other errors as well.

Categories