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
Related
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.
I am new to network automation, and trying to use pyntc to ssh to the device. I am not sure how to write the code correctly to handle the ssh timeout or authentication error, etc.
My code is as below:
from pyntc import ntc_device as NTC
from pyntc_devices_list import Get_Devices_List
all_devices = Get_Devices_List()
for device in all_devices:
print('Backing up ' + device['name'])
DEVICE = NTC(host=device['ip'], username=device['username'], password=device['password'], device_type='cisco_ios$
try:
DEVICE.open()
except Exception:
print('Error')
continue
back_config = DEVICE.backup_running_config(device['name'] + '.cfg')
DEVICE.close()
I manually turned off this device, and then I found python code was quit:
root#Network-Automation:~/Pyntc# python3 pyntc_error_handling.py
Backing up ESW1
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/netmiko/base_connection.py", line 884, in establish_connection
self.remote_conn_pre.connect(**ssh_connect_params)
File "/usr/local/lib/python3.5/dist-packages/paramiko/client.py", line 368, in connect
raise NoValidConnectionsError(errors)
paramiko.ssh_exception.NoValidConnectionsError: [Errno None] Unable to connect to port 22 on 192.168.122.72
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "pyntc_error_handling.py", line 8, in <module>
DEVICE = NTC(host=device['ip'], username=device['username'], password=device['password'], device_type='cisco_ios_ssh')
File "/usr/local/lib/python3.5/dist-packages/pyntc/__init__.py", line 38, in ntc_device
return device_class(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/pyntc/devices/ios_device.py", line 42, in __init__
self.open()
File "/usr/local/lib/python3.5/dist-packages/pyntc/devices/ios_device.py", line 300, in open
verbose=False,
File "/usr/local/lib/python3.5/dist-packages/netmiko/ssh_dispatcher.py", line 246, in ConnectHandler
return ConnectionClass(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/netmiko/base_connection.py", line 317, in __init__
self._open()
File "/usr/local/lib/python3.5/dist-packages/netmiko/base_connection.py", line 322, in _open
self.establish_connection()
File "/usr/local/lib/python3.5/dist-packages/netmiko/base_connection.py", line 890, in establish_connection
raise NetMikoTimeoutException(msg)
netmiko.ssh_exception.NetMikoTimeoutException: Connection to device timed-out: cisco_ios 192.168.122.72:22
Looks like there are more than 1 errors ...
You are doing a minor mistake here, you are expecting an error than trying to same the output. In case of error, the script will through an error. Try it this way.
from pyntc import ntc_device as NTC
from pyntc_devices_list import Get_Devices_List
all_devices = Get_Devices_List()
try:
for device in all_devices:
print('Backing up ' + device['name'])
DEVICE = NTC(host=device['ip'], username=device['username'], password=device['password'], device_type='cisco_ios')
DEVICE.open()
back_config = DEVICE.backup_running_config(device['name'] + '.cfg')
DEVICE.close()
except Exception as Err:
print(Err)
import paramiko
from socket import error as socket_error
import os
server =['10.10.0.1','10.10.0.2']
path='/home/test/'
for hostname in server:
try:
ssh_remote =paramiko.SSHClient()
ssh_remote.set_missing_host_key_policy(paramiko.AutoAddPolicy())
privatekeyfile = os.path.expanduser('~/.ssh/id')
mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile, password='test123')
ssh_remote.connect(hostname, username = 'test1', pkey = mykey)
sftp=ssh_remote.open_sftp()
for i in sftp.listdir(path):
info = sftp.stat(i)
print info.st_size
except paramiko.SSHException as sshException:
print "Unable to establish SSH connection:{0}".format(hostname)
except socket_error as socket_err:
print "Unable to connect connection refused"
This is my code. I tried to get file size of remote server files. But below error was throwing. Can some please guide on this?
Error
Traceback (most recent call last):
File "<stdin>", line 15, in <module>
File "/usr/lib/python2.6/site-packages/paramiko/sftp_client.py", line 337, in stat
t, msg = self._request(CMD_STAT, path)
File "/usr/lib/python2.6/site-packages/paramiko/sftp_client.py", line 624, in _request
return self._read_response(num)
File "/usr/lib/python2.6/site-packages/paramiko/sftp_client.py", line 671, in _read_response
self._convert_status(msg)
File "/usr/lib/python2.6/site-packages/paramiko/sftp_client.py", line 697, in _convert_status
raise IOError(errno.ENOENT, text)
IOError: [Errno 2] No such file
SFTPClient.listdir returns file names only, not a full path. So to use the filename in another API, you have to add a path:
for i in sftp.listdir(path):
info = sftp.stat(path + "/" + i)
print info.st_size
Though that's inefficient. Paramiko knows the size already, you are just throwing the information away by using SFTPClient.listdir instead of SFTPClient.listdir_attr (listdir calls listdir_attr internally).
for i in sftp.listdir_attr(path):
print i.st_size
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.
I have the following problem:
I wrote a FTPHandler(StreamHandler), which connects via 'transport=paramiko.Transport(...)' and 'transport.connect(...)' to a server and opens a sftp connection with 'SFTPClient.from_transport(...)'.
I am importing this handler in a class named 'JUS_Logger.py', which is my module for logging. This 'FMP_Logger' is imported by another class, 'JUS_Reader'.
The problem is, that if I start 'JUS_Reader', the transport is being initialized, but the Connection fails. There is no exception, the program only hangs. If I kill it, I get the stacktrace
CTraceback (most recent call last):
File "./JUS_Reader.py", line 24, in <module>
from JUS_Logger import logger
File "/<home>/.../JUS_Logger.py", line 74, in <module>
ftpHandler=FTPHandler(ftpOut,10)
File "/<home>/FTPHandler.py", line 21, in __init__
self.transport.connect(username=ftpOut['user'].decode('base64'),password=ftpOut['passwd'].decode('base64'))
File "/usr/lib/python2.7/dist-packages/paramiko/transport.py", line 1004, in connect
self.auth_password(username, password)
File "/usr/lib/python2.7/dist-packages/paramiko/transport.py", line 1165, in auth_password
return self.auth_handler.wait_for_response(my_event)
File "/usr/lib/python2.7/dist-packages/paramiko/auth_handler.py", line 158, in wait_for_response
event.wait(0.1)
File "/usr/lib/python2.7/threading.py", line 403, in wait
self.__cond.wait(timeout)
File "/usr/lib/python2.7/threading.py", line 262, in wait
_sleep(delay)
However, if I'm running the 'JUS_Logger.py' by itself, everything works, the transport's connection establishes and the SFTClient connects also.
Any ideas? Or further questions?