我正在构建一个简单的程序,该程序使用Ganymed for SSH2库对Linux服务器执行单个命令。这里是我的代码...System.out.println同时打印
public class Main {
static Scanner reader = new Scanner(System.in);
public static void main(String[] args) throws IOException, InterruptedException{
String hostname; // = "192.168.1.241";
int port; // = 22
String username; // = "root";
String password;
String cmd; // = "echo 'Hello World'";
//ask user for hostname/IP
System.out.print("Enter hostname or IP: ");
hostname = reader.nextLine();
//ask user for port #
System.out.print("Enter port number: ");
port = reader.nextInt();
//create connection
Connection connect = new Connection(hostname, port);
//ask user for username
System.out.println("Enter Username (best to use 'root'): ");
username = reader.nextLine();
//ask user for password
System.out.println("Enter Password: ");
password = reader.nextLine();
System.out.println("Attempting to log in...");
reader.close();
//establish connection
connect.connect();
//login using password
connect.authenticateWithPassword(username, password);
Thread.sleep(1000);
if (Thread.interrupted()) // Clears interrupted status!
throw new InterruptedException();
Boolean didConnect = connect.isAuthenticationComplete();
if (didConnect==false){
throw new IOException("Authentication Unsucessful \nCheck hostname and port number, then try again.");
}
//open session
Session session = connect.openSession();
System.out.println("Opened session!");
System.out.println("Enter a command to execute: ");
cmd = reader.nextLine();
//execute command
session.execCommand(cmd);
//get output
InputStream stdout = new StreamGobbler(session.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
String line = br.readLine();
if (line!=null){
System.out.println("Command sent succesfully!" + "\nOutput: " + "\n" + "\n" + line);
}else{
System.out.println("Command sent succesfully!" + "\nNo Output");
}
//close buffered reader
br.close();
//close session
session.close();
//close connection
connect.close();
}
}
出于某种原因......同时
//ask user for username
System.out.println("Enter Username (best to use 'root'): ");
username = reader.nextLine();
//ask user for password
System.out.println("Enter Password: ");
password = reader.nextLine();
打印,我不知道为什么!当使用打印ln并且在使用打印时在相同的行上,它也在完全不同的行上获得用户输入。
我希望他们先询问用户名,然后再输入密码,将用户输入放在输出旁边。但是,当我要求他们单独/按顺序打印主机名和端口号时,就像我希望的那样。我究竟做错了什么?
谢谢,这工作,很好的解释 –