Skip to content

Instantly share code, notes, and snippets.

@hemanth22
Forked from huskercane/python_ssh_jsch.py
Created June 16, 2023 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hemanth22/c33a709fd51de8bb41dddb953948d7fa to your computer and use it in GitHub Desktop.
Save hemanth22/c33a709fd51de8bb41dddb953948d7fa to your computer and use it in GitHub Desktop.
SSH from jython using jsch
I have to make ssh calls from python, there are few options
however we run in jython and it runs automated, so adding extension is difficult.
luckily we have access to jsch jars.
here is a example on how to connect to a ssh server using jsch from python/jython
from com.jcraft.jsch import JSch
from org.python.core.util import FileUtil
from java.lang import System
jsch=JSch()
host="10.3.407.170"; #intentionally wrong here
user="myuser"
session=jsch.getSession(user, host, 22);
session.setPassword("coolpassword");
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
command="ls"
channel=session.openChannel("exec");
channel.setCommand(command);
# X Forwarding
# channel.setXForwarding(true);
#channel.setInputStream(System.in);
channel.setInputStream(None);
#channel.setOutputStream(System.out);
#FileOutputStream fos=new FileOutputStream("/tmp/stderr");
#((ChannelExec)channel).setErrStream(fos);
channel.setErrStream(System.err);
instream=channel.getInputStream();
channel.connect();
fu = FileUtil.wrap(instream)
for line in fu.readlines():
print line
if channel.isClosed():
print "exit-status: "+channel.getExitStatus()
try:
Thread.sleep(1000)
except:
print e
channel.disconnect();
session.disconnect();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment