2014-12-02 732 views
1

我知道有重複>>>從副本複製>>>只要您的本地計算機有一個運行的SSH服務器< < < < <,但我不能發表評論,不能從問題(和IM不提供答案....)com.jcraft.jsch.JSchException:java.net.ConnectException:連接被拒絕:連接

它說,「只要你的本地機器具有運行SSH服務器」,但我不知道如何運行SSh服務器。我打開我的膩子(雙擊它)(不知道這意味着SSH(?膩子?)服務器(?)正在運行...無疑讓...

IM真正的新Socket編程我。我利用JSch(http://www.jcraft.com/jsch/)來嘗試連接到遠程服務器(後一階段) 目前,這是我使用的代碼和我嘗試連接到我的本地計算機和執行命令(LS是精確的)做一個考驗。不過,我不停的按連接被拒絕,我一派,我注意到,有一些文章,在「有服務器監聽」中提到,但我不知道這意味着什麼。請如下查看我的代碼。

import java.awt.event.*; 

import javax.swing.*; 

import java.awt.*; 
import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.util.Properties; 

import com.jcraft.jsch.*; 



class SwingWorkerExample { 

    JTextField hostField; 
    JTextField userNameField; 
    JTextField passwordField; 
    JPanel panel; 


    public SwingWorkerExample() { 
     JPanel p = panel = new JPanel(new GridLayout(0,2)); 
     hostField = new JTextField(20); 
     userNameField = new JTextField(20); 
     passwordField = new JPasswordField(20); 
     JButton testButton = new JButton("connect!"); 
     testButton.addActionListener(new ActionListener() { 
       public void actionPerformed(ActionEvent ev) { 
        testConnectionButtonActionPerformed(ev); 
       } 
      }); 
     p.add(new JLabel("host:")); 
     //127.0.0.1 
     p.add(hostField); 
     p.add(new JLabel("user:")); 
     //mycomputerusername 
     p.add(userNameField); 
     p.add(new JLabel("password:")); 
     //mycomputerpassword 
     p.add(passwordField); 
     p.add(testButton); 
    } 

    public JPanel getPanel() { 
     return panel; 
    } 

    private void testConnectionButtonActionPerformed(ActionEvent evt) { 

     SwingWorker sw = new SwingWorker(){ 

       protected Object doInBackground() throws Exception { 
        try { 
         JSch jsch = new JSch(); 

         String host = hostField.getText(); 
         String username = userNameField.getText(); 
         String password = passwordField.getText(); 

         Session session = jsch.getSession(username, host); 
         session.setPassword(password); 
         session.setConfig("StrictHostKeyChecking", "no"); 

         session.setTimeout(20000); 
         System.out.println("Connecting to server..."); 
         session.connect(); 

         return session; 
        } 
        catch(Exception ex) { 
         ex.printStackTrace(); 
         throw ex; 
        } 
       } 

       public void done(){ 
        try { 
         System.out.println(get()); 
        } catch (Exception ex) { 
         ex.printStackTrace(); 
        } 
       } 
      }; 

     sw.execute(); 

    } 


    public static void main(String[] egal) { 
     EventQueue.invokeLater(new Runnable(){public void run() { 
      SwingWorkerExample ex = new SwingWorkerExample(); 
      JFrame f = new JFrame("bla"); 
      f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); 
      f.setContentPane(ex.getPanel()); 
      f.pack(); 
      f.setVisible(true); 
     }}); 
    } 

    public void remoteLs() throws JSchException, IOException { 
     JSch js = new JSch(); 
     Session s = js.getSession("kellyseo", "192.168.0.103", 22); 
     s.setPassword("S9031808z"); 
     Properties config = new Properties(); 
     config.put("StrictHostKeyChecking", "no"); 
     s.setConfig(config); 
     s.connect(); 

     Channel c = s.openChannel("exec"); 
     ChannelExec ce = (ChannelExec) c; 

     ce.setCommand("ls -l"); 
     ce.setErrStream(System.err); 

     ce.connect(); 

     BufferedReader reader = new BufferedReader(new InputStreamReader(ce.getInputStream())); 
     String line; 
     while ((line = reader.readLine()) != null) { 
      System.out.println(line); 
     } 

     ce.disconnect(); 
     s.disconnect(); 

     System.out.println("Exit code: " + ce.getExitStatus()); 

     } 



     public void remoteMkdir() throws JSchException, IOException { 
     JSch js = new JSch(); 
     Session s = js.getSession("myusername", "myremotemachine.mycompany.com", 22); 
     s.setPassword("mypassword"); 
     Properties config = new Properties(); 
     config.put("StrictHostKeyChecking", "no"); 
     s.setConfig(config); 
     s.connect(); 

     Channel c = s.openChannel("exec"); 
     ChannelExec ce = (ChannelExec) c; 

     ce.setCommand("mkdir remotetestdir"); 
     ce.setErrStream(System.err); 

     ce.connect(); 

     BufferedReader reader = new BufferedReader(new InputStreamReader(ce.getInputStream())); 
     String line; 
     while ((line = reader.readLine()) != null) { 
      System.out.println(line); 
     } 

     ce.disconnect(); 
     s.disconnect(); 

     System.out.println("Exit code: " + ce.getExitStatus()); 

     } 

     public void remoteCopy() throws JSchException, IOException, SftpException { 
     JSch js = new JSch(); 
     Session s = js.getSession("myusername", "myremotemachine.mycompany.com", 22); 
     s.setPassword("mypassword"); 
     Properties config = new Properties(); 
     config.put("StrictHostKeyChecking", "no"); 
     s.setConfig(config); 
     s.connect(); 

     Channel c = s.openChannel("sftp"); 
     ChannelSftp ce = (ChannelSftp) c; 

     ce.connect(); 

     ce.put("/home/myuser/test.txt","test.txt"); 

     ce.disconnect(); 
     s.disconnect();  
     } 
} 

BTW我使用commandprompt到ping 127.0.0.1是好的,但如果我使用Telnet 127.0.0.1它說無法打開連接到主機(我打開膩子(?雙擊?),端口23:連接失敗。 和SSH = PUTTY ...對嗎? (我不能使用在命令提示 'SSH' 命令)

鏈接: 1)http://sourceforge.net/p/jsch/mailman/message/31745775/

和2)http://javarevisited.blogspot.sg/2013/02/java-net-ConnectException-Connection-refused.html

和3)http://www.jcraft.com/jsch/examples/ 和4)Run a command over SSH with JSch 和5)Can we use JSch for SSH key-based communication?

...感謝提前!

哦,還有這個也是http://www.ganymed.ethz.ch/ssh2/(JSch的替代品..任何建議歡迎!)但是當我嘗試運行該示例時,它說沒有主要。哪個..我duno>。 <將堅持w JSch到那時......

順便說一句,我嘗試https://serverfault.com/questions/185153/free-public-ssh-server-for-testing-purposes服務器,但...我不知道什麼是地址,用戶名和密碼。 (我也有一個http://sdf.org帳戶新建但是當我嘗試連接到它,它說unknownhost。僅供參考!)

忘了提,使用Windows 7 IM和「蔭」是不是我的命令的命令提示...

+0

您需要安裝SSH服務器。膩子只作爲您的SSH客戶端。 – 2014-12-02 04:49:45

回答

5

您正在嘗試通過SSH協議連接到本地主機。使用JSCH這不是完全的套接字編程,但是你的問題與套接字編程有關。

本質上你的問題是你的程序試圖連接到一個未打開的端口,特別是在這個實例中它是22端口。你沒有SSH服務器,所以你的SSH客戶端不能做任何事情。你正在給沒有電話的人撥打電話。

要解決此問題,您需要找到一臺測試服務器,它具有運行ssh的功能,可以針對您的本地PC上的ssh服務器進行開發或安裝該服務器。對於windows系統,你最好的選擇是cygwin,它可以讓你模擬一個posix系統並在本地機器上運行SSHD。谷歌搜索cygwin和sshd將爲您提供如何設置的例子。

+0

嗨,即時通訊目前正試圖通過http://www.techmalaya.com/2009/08/05/setup-ssh-server-for-windows-freesshd/和http://osskb.blogspot.sg/2013/使用freesshd 10/how-to-resolve-you-dont-have.html for admin rights issue。非常感謝!我可以膩子我的本地127.0.0.1,但是當我改掉登錄(通過應用程序GUI,它說EE:com.jcraft.jrexec.JRexecException:JRexec:java.net.ConnectException:連接被拒絕:連接(我創建了一個帳戶通過freesshd user1 pwd user1和檢查所有訪問) – Kelly 2014-12-02 07:12:17

0

我不知道爲什麼,但之後我可以膩子我的本地主機,雖然上述(示例代碼,並感謝您提供的代碼)我面對錯誤,但下面的代碼(再次感謝你們提供的代碼。這個代碼來自JCraft,如果我沒有困惑,工作!我設法發送命令'幫助')。非常感謝#chris midolo提供的答案和#Robby Cornelissen的評論......雖然我變得更加困惑(所以... SSH意味着服務器和客戶端(?)嘆息......而且我通過遠程訪問方式只要我的電腦開着,我就可以從其他地方訪問它...所以我的電腦,爲了從其他地方訪問,還必須有一些服務器運行... OMG!我的頭疼...... )

請注意使用其他命令將導致「無法遠程系統上執行命令或shell「幫助」,除了:無法執行過程。按照http://www.freesshd.com/index.php?ctt=forum&action=view&topic=1186152755,你需要使用cmd /c dir 和執行我的bat文件,我需要使用C:\用戶\ kellyseo \ sampling.bat(如果我只是用sampling.bat,它顯示了一個錯誤)

我的批處理文件內容如下:

ECHO RUNNING kellyseo SAMPLING.BAT 
@ECHO OFF 
CD C:\Users\kellyseo\Desktop 
set ldt=kellyseo folder version executed on %date% %time% 
echo %ldt%>> logs.txt 
EXIT 

我其實有2個版本的同一文件(一個我把在桌面上),那麼我可以只使用「sampling.bat」

如果你不這樣做喜歡許多提示,除了刪除提示,您可能還需要fol如果你面臨這樣com.jcraft.jsch.JSchException降脂代碼:UnknownHostKey(感謝com.jcraft.jsch.JSchException: UnknownHostKey

session.setPassword(password); 
java.util.Properties config = new java.util.Properties(); 
config.put("StrictHostKeyChecking", "no"); 
session.setConfig(config); 
session.connect(); 

**注:#1提示=輸入密碼。 #2提示=輸入命令。用戶名是'user1'

/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ 
/** 
* This program will demonstrate remote exec. 
* $ CLASSPATH=.:../build javac Exec.java 
* $ CLASSPATH=.:../build java Exec 
* You will be asked username, hostname, displayname, passwd and command. 
* If everything works fine, given command will be invoked 
* on the remote side and outputs will be printed out. 
* 
*/ 
import com.jcraft.jsch.*; 
import java.awt.*; 
import javax.swing.*; 
import java.io.*; 

public class Exec{ 
    public static void main(String[] arg){ 
    try{ 
     JSch jsch=new JSch(); 
/* 
     String host=null; 
     if(arg.length>0){ 
     host=arg[0]; 
     } 
     else{ 
     host=JOptionPane.showInputDialog("Enter [email protected]", 
             System.getProperty("user.name")+ 
             "@localhost"); 
     } 
     String user=host.substring(0, host.indexOf('@')); 
     host=host.substring(host.indexOf('@')+1); 
*/ 
     String user1 = "user1"; 
     String host1 = "127.0.0.1"; 
     Session session=jsch.getSession(user1, host1, 22); 

     /* 
     String xhost="127.0.0.1"; 
     int xport=0; 
     String display=JOptionPane.showInputDialog("Enter display name", 
               xhost+":"+xport); 
     xhost=display.substring(0, display.indexOf(':')); 
     xport=Integer.parseInt(display.substring(display.indexOf(':')+1)); 
     session.setX11Host(xhost); 
     session.setX11Port(xport+6000); 
     */ 

     // username and password will be given via UserInfo interface. 
     UserInfo ui=new MyUserInfo(); 
     session.setUserInfo(ui); 
     session.connect(); 

     String command=JOptionPane.showInputDialog("Enter command", 
               "set|grep SSH"); 

     Channel channel=session.openChannel("exec"); 
     ((ChannelExec)channel).setCommand(command); 

     // X Forwarding 
     // channel.setXForwarding(true); 

     //channel.setInputStream(System.in); 
     channel.setInputStream(null); 

     //channel.setOutputStream(System.out); 

     //FileOutputStream fos=new FileOutputStream("/tmp/stderr"); 
     //((ChannelExec)channel).setErrStream(fos); 
     ((ChannelExec)channel).setErrStream(System.err); 

     InputStream in=channel.getInputStream(); 

     channel.connect(); 

     byte[] tmp=new byte[1024]; 
     while(true){ 
     while(in.available()>0){ 
      int i=in.read(tmp, 0, 1024); 
      if(i<0)break; 
      System.out.print(new String(tmp, 0, i)); 
     } 
     if(channel.isClosed()){ 
      if(in.available()>0) continue; 
      System.out.println("exit-status: "+channel.getExitStatus()); 
      break; 
     } 
     try{Thread.sleep(1000);}catch(Exception ee){} 
     } 
     channel.disconnect(); 
     session.disconnect(); 
    } 
    catch(Exception e){ 
     System.out.println(e); 
    } 
    } 

    public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{ 
    public String getPassword(){ return passwd; } 
    public boolean promptYesNo(String str){ 
     Object[] options={ "yes", "no" }; 
     int foo=JOptionPane.showOptionDialog(null, 
      str, 
      "Warning", 
      JOptionPane.DEFAULT_OPTION, 
      JOptionPane.WARNING_MESSAGE, 
      null, options, options[0]); 
     return foo==0; 
    } 

    String passwd; 
    JTextField passwordField=(JTextField)new JPasswordField(20); 

    public String getPassphrase(){ return null; } 
    public boolean promptPassphrase(String message){ return true; } 
    public boolean promptPassword(String message){ 
     Object[] ob={passwordField}; 
     int result= 
     JOptionPane.showConfirmDialog(null, ob, message, 
             JOptionPane.OK_CANCEL_OPTION); 
     if(result==JOptionPane.OK_OPTION){ 
     passwd=passwordField.getText(); 
     return true; 
     } 
     else{ 
     return false; 
     } 
    } 
    public void showMessage(String message){ 
     JOptionPane.showMessageDialog(null, message); 
    } 
    final GridBagConstraints gbc = 
     new GridBagConstraints(0,0,1,1,1,1, 
          GridBagConstraints.NORTHWEST, 
          GridBagConstraints.NONE, 
          new Insets(0,0,0,0),0,0); 
    private Container panel; 
    public String[] promptKeyboardInteractive(String destination, 
               String name, 
               String instruction, 
               String[] prompt, 
               boolean[] echo){ 
     panel = new JPanel(); 
     panel.setLayout(new GridBagLayout()); 

     gbc.weightx = 1.0; 
     gbc.gridwidth = GridBagConstraints.REMAINDER; 
     gbc.gridx = 0; 
     panel.add(new JLabel(instruction), gbc); 
     gbc.gridy++; 

     gbc.gridwidth = GridBagConstraints.RELATIVE; 

     JTextField[] texts=new JTextField[prompt.length]; 
     for(int i=0; i<prompt.length; i++){ 
     gbc.fill = GridBagConstraints.NONE; 
     gbc.gridx = 0; 
     gbc.weightx = 1; 
     panel.add(new JLabel(prompt[i]),gbc); 

     gbc.gridx = 1; 
     gbc.fill = GridBagConstraints.HORIZONTAL; 
     gbc.weighty = 1; 
     if(echo[i]){ 
      texts[i]=new JTextField(20); 
     } 
     else{ 
      texts[i]=new JPasswordField(20); 
     } 
     panel.add(texts[i], gbc); 
     gbc.gridy++; 
     } 

     if(JOptionPane.showConfirmDialog(null, panel, 
             destination+": "+name, 
             JOptionPane.OK_CANCEL_OPTION, 
             JOptionPane.QUESTION_MESSAGE) 
     ==JOptionPane.OK_OPTION){ 
     String[] response=new String[prompt.length]; 
     for(int i=0; i<prompt.length; i++){ 
      response[i]=texts[i].getText(); 
     } 
    return response; 
     } 
     else{ 
     return null; // cancel 
     } 
    } 
    } 
} 
0

如果您使用的是mac,您可能沒有允許遠程登錄服務器(在本例中爲您的機器)。轉至系統偏好設置 - >共享並啓用遠程登錄。還要添加您想要使用的用戶。