I have built below simple python code to connect to one of my webserver.
import paramiko
# Set up SSH client
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Set up connection details
ip = "10.218.16.16"
user = "user1"
password = "234!!!lem600@HW"
# Connect to server
try:
ssh.connect(ip, username=user, password=password)
print(f"Successfully logged in as {ssh.exec_command('whoami')[1].read().decode().strip()}")
except paramiko.ssh_exception.AuthenticationException:
print("Authentication failed")
except paramiko.ssh_exception.SSHException:
print("Unable to establish SSH connection")
finally:
ssh.close()
This works fine. After connecting to this webserver, I am performing below steps in putty.
so what I need is to do the above also in same code... I have added below part also..
ip2 = "hadoopc1h1"
user2 = "user2"
password2 = "235!!!lem600@HW"
try:
# Execute ssh command to connect to second server
_, stdout, _ = ssh1.exec_command(f'ssh {user2}@{ip2}')
stdin = stdout.channel.makefile("wb")
stdin.write(f"{password2}\n".encode())
stdin.flush()
# Print output of ssh command to second server
print(stdout.read().decode())
Here what I am getting
OSError: Socket is closed
Network connectivity is also available...can someone help me?
Tying to automate an interactive shell is usually wrong approach and will cause you troubles. Your attempt with exec_command
is definitely a better start. See also
Providing input/subcommands to command executed over SSH with JSch
Though you might be actually looking for
How to SSH to a server behind another SSH server using JSch?