paramiko.SSHException: Channel closed - python

I try to use python 2.7.1 and paramiko 1.12.0:
connection = paramiko.SSHClient()
connection.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
connection.set_missing_host_key_policy(paramiko.AutoAddPolicy())
connection.connect(hostIP, 22, 'd', 'd')
command = 'ls'
(stdin, stdout, stderr) = connection.exec_command(command)
response = stdout.readlines()
errormsg = stderr.read()
But I get this error message:
Traceback (most recent call last):<br>
File "./ssh.py", line 32, in <module><br>
(stdin, stdout, stderr) = connection.exec_command(command)<br>
File "/app/python/2.7.1/LMWP3/lib/python2.7/site-packages/paramiko/client.py", line 379, in exec_command<br>
chan.exec_command(command)<br>
File "/app/python/2.7.1/LMWP3/lib/python2.7/site-packages/paramiko/channel.py", line 218, in exec_command<br>
self._wait_for_event()<br>
File "/app/python/2.7.1/LMWP3/lib/python2.7/site-packages/paramiko/channel.py", line 1129, in _wait_for_event<br>
raise e<br>
paramiko.SSHException: Channel closed.

import paramiko
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
conn = s.connect(hostIP, username ='root', password='rootpassword', port=22)
command = 'pwd'
(stdin, stdout, stderr) = s.exec_command(command)
print stdout.read()
s.close()
This should work fine with root user on linux. If it's not, you are probably passing wrong values for hostIP (for ex: quotes in the value), username, password.

Related

Paramiko Authentication Failed?

I have tried to fix it up but got the same error every time. I have tried several times also tried in google but cannot give a suitable answer.
def ssh(hostname, command):
sshcon = paramiko.SSHClient()
logging.basicConfig()
sshcon.load_system_host_keys()
sshcon.set_missing_host_key_policy(paramiko.AutoAddPolicy())
sshcon.connect(hostname, username='root', password='password')
stdin, stdout, stderr = sshcon.exec_command(command)
return stdout.read()
while True:
i = 1
while i <= 60:
print "|------- Webserver2 -----------|"
print time.ctime()
response_time(desired_response_time, url2, webserver2, bilal2, local)
list=ssh(bilal2, "xm list")
if "webserver1" in list:
horizontal('2')
print "|------- Webserver1 -----------|"
response_time(desired_response_time, url1, webserver1, bilal2, local)
else:
horizontal('1')
pass
time.sleep(5)
i += 1
The error
Error:
Traceback (most recent call last):
File "newcodepid.py", line 472, in <module>
list=ssh(bilal2, "xm list")
File "newcodepid.py", line 61, in ssh
sshcon.connect(hostname, username='root', password='password')
File "/usr/lib/python2.7/dist-packages/paramiko/client.py", line 332, in connect
self._auth(username, password, pkey, key_filenames, allow_agent, look_for_keys)
File "/usr/lib/python2.7/dist-packages/paramiko/client.py", line 493, in _auth
raise saved_exception
paramiko.AuthenticationException: Authentication failed.

paramiko sftp can't delete remote folder, ioerror

This is my code, to delete a remote directory using paramiko sftp.
import paramiko
host = "192.168.1.13"
port = 22
transport = paramiko.Transport((host, port))
username = "root"
password = "abc123"
transport.connect(username = username, password = password)
sftp = paramiko.SFTPClient.from_transport(transport)
filepath = '/root/test_folder'
sftp.rmdir(filepath)
Execute above code will output this error,
Traceback (most recent call last):
File "autom_test.py", line 36, in <module>
sftp.rmdir(filepath)
File "/usr/lib/python2.7/site-packages/paramiko/sftp_client.py", line 390, in rmdir
self._request(CMD_RMDIR, path)
File "/usr/lib/python2.7/site-packages/paramiko/sftp_client.py", line 729, in _request
return self._read_response(num)
File "/usr/lib/python2.7/site-packages/paramiko/sftp_client.py", line 776, in _read_response
self._convert_status(msg)
File "/usr/lib/python2.7/site-packages/paramiko/sftp_client.py", line 806, in _convert_status
raise IOError(text)
IOError: Failure
This is not the case when I'm using sftp.remove(path) for a single file. But sftp.rmdir causing IOError
The syntax is from the documentation.
The error is because the destination directory has got files inside it.
Try recurssive delete instead.. See below..
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host,username=username,password=password)
filepath="/root/test_folder"
cmd = "rm -rf " + filepath
stdin, stdout, stderr = ssh.exec_command(cmd)
while not stdout.channel.exit_status_ready():
time.sleep(5)

Python Paramiko SSH run command

I want to run simple command just for test ssh connection. There is an error about stdin/out/err. Code and error mesage is below.
Can someone help me ?
Code
import paramiko
import sys
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('x.x.x.x', port=2222, username='user', password='pass')
stdin, stdout, stderr = client.exec_command('exit')
print stdout
client.close()
Error message
Traceback (most recent call last):
File "C:/Users/EXT03D3912/PycharmProjects/paramiko_ssh1/paramiko_ssh1.py", line 9, in <module>
stdin, stdout, stderr = client.exec_command('exit')
File "build\bdist.win32\egg\paramiko\client.py", line 343, in exec_command
File "build\bdist.win32\egg\paramiko\channel.py", line 212, in exec_command
File "build\bdist.win32\egg\paramiko\channel.py", line 1081, in _wait_for_event
EOFError
thanks,
haktan
Since you are logged out from the terminal it is giving a EOFError AFAIK you can just close the connection it will automatically close your session there.
Consider the following code
import paramiko
import sys
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('x.x.x.x', port=2222, username='user', password='pass')
stdin, stdout, stderr = client.exec_command('ls')
print stdout
client.close()

paramiko/ Socket closes after returning console object from function

I try to return socket object from function, but after return socket immediatly closes. Any help is greatly appreciated :) Thanks
def get_connection(ip, log, paswd):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, username=log, password=paswd, timeout=100)
console = ssh.invoke_shell()
print(console)
return console
def get_version(console, host):
promt = console.recv(1000)
if '>' in str(promt):
console.send('enable\n')
console.send('P#ssw0rd\n')
console.send('terminal length 0\n')
console.send('show version\n')
time.sleep(2)
out = console.recv(5000).decode('utf-8')
system_version_finder = re.search('#show version\r\n(.+)', out)
if system_version_finder:
system_version = system_version_finder.group(1)
else:
system_version = 'Unknown'
print(host + '\s' + system_version)
def upload_config(console, file_path):
console.send('configure terminal\n')
with open(file_path, 'r') as config_file:
for line in config_file:
console.send(line)
for host in options.ip_address_list:
console = get_connection(host, options.login, options.password)
print(console)
get_version(console, host)
if options.conf_file_path:
upload_config(console, options.conf_file_path)
This is output of script:
<paramiko.Channel 0 (open) window=1024 -> <paramiko.Transport at 0x34f5e10 (cipher aes128-cbc, 128 bits) (active; 1 open channel(s))>>
<paramiko.Channel 0 (closed) -> <paramiko.Transport at 0x34f5e10 (unconnected)>>
Traceback (most recent call last):
File "llearn.py", line 65, in <module>
get_version(console, host)
File "llearn.py", line 32, in get_version
console.send('terminal length 0\n')
File "C:\Program Files (x86)\Python\lib\site-packages\paramiko-1.16.0-py3.4.egg\paramiko\channel.py", line 698, in send
File "C:\Program Files (x86)\Python\lib\site-packages\paramiko-1.16.0-py3.4.egg\paramiko\channel.py", line 1058, in _send
OSError: Socket is closed
Hmm, I think the contents of ssh in get_connection might be garbage collected after the function returns, because paramiko isn't holding on to it in console.
Try:
def get_connection(ip, log, paswd):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, username=log, password=paswd, timeout=100)
console = ssh.invoke_shell()
console.keep_this = ssh
print(console)
return console
Note we're now storing a reference to ssh on console.
On FreeBSD, your version doesn't produce errors, but it doesn't seem to work either. Adding that line makes it work for me.

Python Paramiko Error

I wrote a python program. I have conf file, I wrote router configuration commands inside the conf file and I want to execute these commands inside paramiko. I have a problem - the error message is below. Can you help me please ?
CODE:
#!/usr/bin/env python
import paramiko
ip="10.100.1.200"
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,username="admin",password="pass")
text=open("conf")
for komut in text.readlines():
stdin, stdout, stderror = ssh.exec_command(komut)
for line in stdout.readlines():
print line.strip()
ssh.close()
text.close()
error message:
Traceback (most recent call last):
File "./configmaker.py", line 13, in <module>
stdin, stdout, stderror = ssh.exec_command(str(komut.strip()))
File "/usr/lib/python2.7/dist-packages/paramiko/client.py", line 370, in exec_command
chan = self._transport.open_session()
File "/usr/lib/python2.7/dist-packages/paramiko/transport.py", line 662, in open_session
return self.open_channel('session')
File "/usr/lib/python2.7/dist-packages/paramiko/transport.py", line 764, in open_channel
raise e
EOFError
Try with this code:
import paramiko
if __name__ == "__main__":
ip = "127.0.0.1"
username = "admin"
password = "root"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,username=username,password=password)
ssh_transport = ssh.get_transport()
for command in ("ls /tmp", "date"):
chan = ssh_transport.open_session()
chan.exec_command(command)
exit_code = chan.recv_exit_status()
stdin = chan.makefile('wb', -1) # pylint: disable-msg=W0612
stdout = chan.makefile('rb', -1)
stderr = chan.makefile_stderr('rb', -1) # pylint: disable-msg=W0612
output = stdout.read()
print output
Try this code, first copy the conf file to remote server and execute the file.
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
host = str(host)
user = 'root'
pw = 'root123'
ssh.connect(host, username=user, password=pw)
filepath = "conf"
remote_path = "/root/qats_tool.tar"
sftp = ssh.open_sftp()
sftp.put(filepath, remote_path)
command="./conf"
stdin, stdout, stderr = ssh.exec_command(command)
sftp.close()

Categories

Resources