private void OpenSSH() { string host = "1.119.7.235"; string user = "******"; string pwd = ""; //SshShell shell = new SshShell(host, user); //ssh JSch jsch = new JSch(); //String file = InputForm.GetFileFromUser(@"E:\A工作文件\AVC CleanData\AVC CleanData\id_rsa_2048.2048"); string file = @"E:\A工作文件\AVC CleanData\AVC CleanData\id_rsa_2048.2048"; jsch.addIdentity(file); Session session = jsch.getSession(user, host); UserInfo ui = new MyUserInfo(); session.setUserInfo(ui); try { session.connect(); // Channel channel = session.openChannel("shell"); } catch (Exception e) { Debug.WriteLine(e); } finally { session.disconnect(); } }
public static void Main(String[] arg) { try { //Create a new JSch instance JSch jsch=new JSch(); //Prompt for username and server host Console.WriteLine("Please enter the user and host info at the popup window..."); String host = InputForm.GetUserInput ("Enter username@hostname", Environment.UserName+"@localhost"); String user=host.Substring(0, host.IndexOf('@')); host=host.Substring(host.IndexOf('@')+1); //Create a new SSH session Session session=jsch.getSession(user, host, 22); // username and password will be given via UserInfo interface. UserInfo ui=new MyUserInfo(); session.setUserInfo(ui); //Add AES128 as default cipher in the session config store System.Collections.Hashtable config=new System.Collections.Hashtable(); config.Add("cipher.s2c", "aes128-cbc,3des-cbc"); config.Add("cipher.c2s", "aes128-cbc,3des-cbc"); session.setConfig(config); //Connect to remote SSH server session.connect(); //Open a new Shell channel on the SSH session Channel channel=session.openChannel("shell"); //Redirect standard I/O to the SSH channel channel.setInputStream(Console.OpenStandardInput()); channel.setOutputStream(Console.OpenStandardOutput()); //Connect the channel channel.connect(); Console.WriteLine("-- Shell channel is connected using the {0} cipher", session.getCipher()); //Wait till channel is closed while(!channel.isClosed()) { System.Threading.Thread.Sleep(500); } //Disconnect from remote server channel.disconnect(); session.disconnect(); } catch(Exception e) { Console.WriteLine(e); } }
public static void Connect() { try { JSch jsch = new JSch(); _session = jsch.getSession(Settings.SSHUsername, Settings.SSHHost, Settings.SSHPort); _session.setHost(Settings.SSHHost); _session.setPassword(Settings.SSHPassword); UserInfo ui = new MyUserInfo(Settings.SSHPassword); _session.setUserInfo(ui); _session.connect(); int port; if (!int.TryParse(Settings.Port, out port)) { port = 3306; } _session.setPortForwardingL(Settings.SSHLocalPort, "localhost", port); if (!_session.isConnected()) { Enabled = false; } } catch (Exception ex) { Enabled = false; Trace.WriteLine(ex.Message + " at ssh connect."); Disconnect(); } }
public SshHelper(string host, string username, string password) { this.host = host; JSch jsch = new JSch(); Session session = jsch.getSession(username, host, 22); session.setPassword(password); Hashtable config = new Hashtable(); config.Add("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); channel = (ChannelShell)session.openChannel("shell"); writer_po = new PipedOutputStream(); PipedInputStream writer_pi = new PipedInputStream(writer_po); PipedInputStream reader_pi = new PipedInputStream(); PipedOutputStream reader_po = new PipedOutputStream(reader_pi); reader = new StreamReader(reader_pi, Encoding.UTF8); channel.setInputStream(writer_pi); channel.setOutputStream(reader_po); channel.connect(); channel.setPtySize(132, 132, 1024, 768); }
static void Main(string[] args) { Sftp sftp = new Sftp(SFTPConnectSample.Properties.Settings.Default.HostName, SFTPConnectSample.Properties.Settings.Default.UserName, SFTPConnectSample.Properties.Settings.Default.Password); sftp.Connect(); #region Require if you want to delete Files JSch objjsh = new JSch(); Session session = objjsh.getSession(SFTPConnectSample.Properties.Settings.Default.UserName, SFTPConnectSample.Properties.Settings.Default.HostName); // Get a UserInfo object UserInfo ui = new UInfo(SFTPConnectSample.Properties.Settings.Default.Password);; // Pass user info to session session.setUserInfo(ui); // Open the session session.connect(); Channel channel = session.openChannel("sftp"); ChannelSftp cSftp = (ChannelSftp)channel; cSftp.connect(); #endregion ArrayList res = sftp.GetFileList(SFTPConnectSample.Properties.Settings.Default.FromPath + "*.xml"); foreach (var item in res) { if (item.ToString() != "." && item.ToString() != "..") { //File Copy from Remote sftp.Get(SFTPConnectSample.Properties.Settings.Default.FromPath + item, Path.Combine(Application.StartupPath, SFTPConnectSample.Properties.Settings.Default.DirectoryPath + "/" + item)); //File Delete from Remote cSftp.rm(SFTPConnectSample.Properties.Settings.Default.FromPath + item); //Upload File sftp.Put(Path.Combine(Path.Combine(Application.StartupPath, "XMLFiles"), item.ToString()), SFTPConnectSample.Properties.Settings.Default.ToPath + item); } } channel.disconnect(); cSftp.exit(); sftp.Close(); }
/// <summary> /// Constructs a new SSH instance /// </summary> /// <param name="sftpHost">The remote SSH host</param> /// <param name="user">The login username</param> /// <param name="password">The login password</param> public SshBase(string sftpHost, string user, string password) { this.m_host = sftpHost; this.m_user = user; this.Password = password; m_jsch = new JSch(); }
internal bool SSHConnect() { try { channels_ = new Dictionary <int, ChannelSftp>(); jsch_ = new JSch(); Hashtable config = new Hashtable(); config["StrictHostKeyChecking"] = "no"; if (identity_ != null) { jsch_.addIdentity(identity_, passphrase_); } session_ = jsch_.getSession(user_, host_, port_); session_.setConfig(config); session_.setUserInfo(new DokanUserInfo(password_, passphrase_)); session_.setPassword(password_); session_.connect(); return(true); } catch (Exception e) { Debug(e.ToString()); return(false); } }
public static void Run() { JSch jsch = new JSch(); Session session = jsch.getSession("root", "rhmanage", 22); session.setPassword("cisco"); Hashtable config = new Hashtable(); config.Add("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); Channel channel = session.openChannel("exec"); ((ChannelExec)channel).setCommand("ifconfig"); StreamReader sr = new StreamReader(channel.getInputStream()); channel.connect(); string line; while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } channel.disconnect(); session.disconnect(); }
// there is no built in way to delete a file using this utility, so we have to hack a bit... // info found here: http://revdoniv.wordpress.com/2010/09/11/how-to-delete-an-sftp-file-in-net/ internal void DeleteFile(string fileName) { var filePath = Path.Combine(_defaultDirectory, fileName); try { var session = new JSch().getSession(Properties.Settings.Default.SFTPUser, Properties.Settings.Default.SFTPHost, Properties.Settings.Default.SFTPPort); // you would think this would work, but nope... it doesnt... //session.setPassword(Properties.Settings.Default.SFTPPass); // you have to override this silly class session.setUserInfo(new SFTPUserInfo(Properties.Settings.Default.SFTPPass)); session.connect(); var sftpChannel = (ChannelSftp)session.openChannel("sftp"); sftpChannel.connect(); sftpChannel.rm(filePath); sftpChannel.disconnect(); session.disconnect(); } catch (Exception ex) { GlobalContext.Log("Unable to delete file from SFTP", true); GlobalContext.Log(ex.ToString(), true); } }
public static void Main(String[] arg) { try { //Create a new JSch instance JSch jsch = new JSch(); //Prompt for username and server host Console.WriteLine("Please enter the user and host info at the popup window..."); String host = InputForm.GetUserInput ("Enter username@hostname", Environment.UserName + "@localhost"); String user = host.Substring(0, host.IndexOf('@')); host = host.Substring(host.IndexOf('@') + 1); //Create a new SSH session Session session = jsch.getSession(user, host, 22); // username and password will be given via UserInfo interface. UserInfo ui = new MyUserInfo(); session.setUserInfo(ui); //Add AES128 as default cipher in the session config store System.Collections.Hashtable config = new System.Collections.Hashtable(); config.Add("cipher.s2c", "aes128-cbc,3des-cbc"); config.Add("cipher.c2s", "aes128-cbc,3des-cbc"); session.setConfig(config); //Connect to remote SSH server session.connect(); //Open a new Shell channel on the SSH session Channel channel = session.openChannel("shell"); //Redirect standard I/O to the SSH channel channel.setInputStream(Console.OpenStandardInput()); channel.setOutputStream(Console.OpenStandardOutput()); //Connect the channel channel.connect(); Console.WriteLine("-- Shell channel is connected using the {0} cipher", session.getCipher()); //Wait till channel is closed while (!channel.isClosed()) { System.Threading.Thread.Sleep(500); } //Disconnect from remote server channel.disconnect(); session.disconnect(); } catch (Exception e) { Console.WriteLine(e); } }
/// <summary> /// Initializes connection to a remote Server with given credentials /// </summary> private void _Init() { if (_jsch != null) { try { Console.WriteLine("Attempting to disconnect"); _sftpSession.disconnect(); _sftpSession = null; _jsch = null; } catch (Exception e) { _sftpSession = null; _jsch = null; Console.WriteLine("There was a failure while restarting connection " + e.Message); } //wait half a second before reconnecting so we dont flood FTP server with continued failed attempts Thread.Sleep(500); } try { _jsch = new JSch(); _sftpSession = _jsch.getSession(_user, _host, _port); _ui = new SftpUserInfo(); // this is needed for the passkey _sftpSession.setUserInfo(_ui); _sftpSession.setPassword(_pass); _sftpSession.connect(); _channel = _sftpSession.openChannel("sftp"); _channel.connect(); _sftpChannel = (ChannelSftp)_channel; //_ins = Console.OpenStandardInput(); //_outs = Console.Out; this.changeRemoteWorkingDirectory(_rootDir); } catch (Exception e) { if (!_reportOnce && _failCount >= 500) { string failMsg = string.Format("SFTP Connection is failing ({2}@{0}:{1}) \n\t{3}", _host, _port, _user, e.Message); GatLogger.Instance.AddMessage(failMsg, LogMode.LogAndScreen); GatLogger.Instance.AddMessage(string.Format("Inner Exception: {0}", e.InnerException)); GatLogger.Instance.AddMessage(string.Format("Exception Stack: {0}", e.StackTrace)); _reportOnce = true; } else { _failCount++; } } }
/// <summary> /// Constructs a new SSH instance /// </summary> /// <param name="sftpHost">The remote SSH host</param> /// <param name="user">The login username</param> /// <param name="password">The login password</param> public SshBase(string sftpHost, int port, string user, string password) { this.m_host = sftpHost; SSH_TCP_PORT = port; this.m_user = user; this.Password = password; m_jsch = new JSch(); }
/// <param name="fs"> /// the file system abstraction which will be necessary to /// perform certain file system operations. /// </param> /// <returns>the new default JSch implementation.</returns> /// <exception cref="NSch.JSchException">known host keys cannot be loaded.</exception> protected internal virtual JSch CreateDefaultJSch(FS fs) { JSch jsch = new JSch(); KnownHosts(jsch, fs); Identities(jsch, fs); return(jsch); }
protected static JSch createDefaultJSch() { JSch jsch = new JSch(); knownHosts(jsch); identities(jsch); return(jsch); }
public static void Main(String[] arg) { try { JSch jsch=new JSch(); //Get the private key filename from the user Console.WriteLine("Please choose your private key file..."); String file = InputForm.GetFileFromUser("Choose your privatekey(ex. ~/.ssh/id_dsa)"); Console.WriteLine("You chose "+file+"."); //Add the identity file to JSch jsch.addIdentity(file); //Prompt for username and server host Console.WriteLine("Please enter the user and host info at the popup window..."); String host = InputForm.GetUserInput ("Enter username@hostname", Environment.UserName+"@localhost"); String user=host.Substring(0, host.IndexOf('@')); host=host.Substring(host.IndexOf('@')+1); //Create a new SSH session Session session=jsch.getSession(user, host, 22); // username and password will be given via UserInfo interface. UserInfo ui=new MyUserInfo(); session.setUserInfo(ui); //Connect to remote SSH server session.connect(); //Open a new Shell channel on the SSH session Channel channel=session.openChannel("shell"); //Redirect standard I/O to the SSH channel channel.setInputStream(Console.OpenStandardInput()); channel.setOutputStream(Console.OpenStandardOutput()); //Connect the channel channel.connect(); //Wait till channel is closed while(!channel.isClosed()) { System.Threading.Thread.Sleep(500); } //Disconnect from remote server channel.disconnect(); session.disconnect(); } catch(Exception e) { Console.WriteLine(e); } }
/// <summary> /// Attempts to re-establish a connection with a remote server /// </summary> /// <returns>true if re-connection succeded or false if re-connection did not succed</returns> private bool _Reconnect() { try { if (_sftpSession != null && !_sftpSession.isConnected()) { //Attempt to reconnect to server if (_sftpChannel != null) { _sftpChannel.disconnect(); } if (_channel != null) { _channel.disconnect(); } _sftpChannel = null; _channel = null; _sftpSession = null; _jsch = null; _jsch = new JSch(); _sftpSession = _jsch.getSession(_user, _host, 22); _sftpSession.setUserInfo(_ui); _sftpSession.setPassword(_pass); _sftpSession.connect(); _channel = _sftpSession.openChannel("sftp"); _channel.connect(); _sftpChannel = (ChannelSftp)_channel; _ChangeRemoteWorkingDirectory(_rootDir); return(true); } } catch (SftpException sftp) { GatLogger.Instance.AddMessage(string.Format("Sftp Exception encountered attempting to reconnect: {0}", sftp.message), LogMode.LogAndScreen); GatLogger.Instance.AddMessage("InnerException: " + sftp.InnerException); GatLogger.Instance.AddMessage("StackTrace: " + sftp.StackTrace); return(false); } catch (Exception ex) { if (ex.Message.Contains("actively refused")) { GatLogger.Instance.AddMessage("**** FTP error Check machine " + _host + " it may be inactive ******", LogMode.LogAndScreen); } else { GatLogger.Instance.AddMessage("An exception occurred while attempting to reconnect on host " + _host + ":" + _user + " :\n" + ex.Message, LogMode.LogAndScreen); } return(false); } return(false); }
public virtual void FtpPickUp(string destinationFilePath, Dictionary <string, string> config, string fileName) { ChannelSftp channelSftp = null; Channel channel; var printxml = config["printxml"] == "true"; var url = config["sftpUrl"]; var username = config["sftpUsername"]; var password = config["sftpPassword"]; var knownHostsFile = config["knownHostsFile"]; var jsch = new JSch(); jsch.setKnownHosts(knownHostsFile); var session = jsch.getSession(username, url); session.setPassword(password); try { session.connect(); channel = session.openChannel("sftp"); channel.connect(); channelSftp = (ChannelSftp)channel; } catch (SftpException e) { throw new LitleOnlineException("Error occured while attempting to establish an SFTP connection", e); } try { if (printxml) { Console.WriteLine("Picking up remote file outbound/" + fileName + ".asc"); Console.WriteLine("Putting it at " + destinationFilePath); } channelSftp.get("outbound/" + fileName + ".asc", destinationFilePath); if (printxml) { Console.WriteLine("Removing remote file output/" + fileName + ".asc"); } channelSftp.rm("outbound/" + fileName + ".asc"); } catch (SftpException e) { throw new LitleOnlineException( "Error occured while attempting to retrieve and save the file from SFTP", e); } channelSftp.quit(); session.disconnect(); }
public static void RunExample(String[] arg) { try { JSch jsch = new JSch(); //Get the "known hosts" filename from the user Console.WriteLine("Please choose your private key file..."); String file = InputForm.GetFileFromUser("Choose your privatekey(ex. ~/.ssh/id_dsa)"); Console.WriteLine("You chose " + file + "."); //Add the identity file to JSch jsch.addIdentity(file); //Prompt for username and server host Console.WriteLine("Please enter the user and host info at the popup window..."); String host = InputForm.GetUserInput ("Enter username@hostname", Environment.UserName + "@localhost"); String user = host.Substring(0, host.IndexOf('@')); host = host.Substring(host.IndexOf('@') + 1); //Create a new SSH session Session session = jsch.getSession(user, host, 22); // username and password will be given via UserInfo interface. UserInfo ui = new MyUserInfo(); session.setUserInfo(ui); //Connect to remote SSH server session.connect(); //Open a new Shell channel on the SSH session Channel channel = session.openChannel("shell"); //Redirect standard I/O to the SSH channel channel.setInputStream(Console.OpenStandardInput()); channel.setOutputStream(Console.OpenStandardOutput()); //Connect the channel channel.connect(); //Wait till channel is closed while (!channel.isClosed()) { System.Threading.Thread.Sleep(500); } //Disconnect from remote server channel.disconnect(); session.disconnect(); } catch (Exception e) { Console.WriteLine(e); } }
public String getFingerPrint(JSch jsch) { HASH hash=null; try{ hash=(HASH)Activator.CreateInstance(Type.GetType(jsch.getConfig("md5"))); } catch(Exception e){ Console.Error.WriteLine("getFingerPrint: "+e); } return Util.getFingerPrint(hash, key); }
public override void Connect(string Host, int Port, string Username, string Password, int timeout = 10000) { this.Host = Host; this.Port = Port; this.Username = Username; this.Password = Password; this.timeout = timeout; _jsch = null; }
private JSch getDefaultJSch() { if (defaultJSch == null) { defaultJSch = createDefaultJSch(); // no identity file support } return(defaultJSch); }
/// <summary> /// Attempts to re-establish a connection with a remote server /// </summary> /// <returns>true if re-connection succeded or false if re-connection did not succed</returns> private bool _Reconnect() { try { if (!_sftpSession.isConnected()) { //Attempt to reconnect to server if (_sftpChannel != null) { _sftpChannel.disconnect(); } if (_channel != null) { _channel.disconnect(); } _sftpChannel = null; _channel = null; _sftpSession = null; _jsch = null; _jsch = new JSch(); _sftpSession = _jsch.getSession(_user, _host, 22); _sftpSession.setUserInfo(_ui); _sftpSession.setPassword(_pass); _sftpSession.connect(); _channel = _sftpSession.openChannel("sftp"); _channel.connect(); _sftpChannel = (ChannelSftp)_channel; this.changeRemoteWorkingDirectory(_rootDir); return(true); } } catch (SftpException sftp) { //Sftp Connection return(false); } catch (Exception ex) { if (ex.Message.Contains("actively refused")) { Console.WriteLine("**** FTP error Check machine " + _host + " it may be inactive ******"); } else { Console.WriteLine("An exception occurred while attempting to reconnect on host " + _host + ":" + _user + " :\n" + ex.Message); } return(false); } return(false); }
private void SetSFTPPara(string user, string ip, string pwd, int port) { JSch jsch = new JSch(); m_session = jsch.getSession(user, ip, port); MyUserInfo ui = new MyUserInfo(); ui.setPassword(pwd); m_session.setUserInfo(ui); }
private void SetSFTPPara(string user, string ip, int port) { JSch jsch = new JSch(); jsch.addIdentity(Application.StartupPath + @"/id_rsa"); m_session = jsch.getSession(user, ip, port); MyUserInfo ui = new MyUserInfo(); m_session.setUserInfo(ui); }
public static void RunExample(String[] arg) { try { JSch jsch=new JSch(); OpenFileDialog chooser = new OpenFileDialog(); chooser.Title ="Choose your privatekey(ex. ~/.ssh/id_dsa)"; //chooser.setFileHidingEnabled(false); DialogResult returnVal = chooser.ShowDialog(); if(returnVal == DialogResult.OK) { Console.WriteLine("You chose "+ chooser.FileName+"."); jsch.addIdentity(chooser.FileName // , "passphrase" ); } else { Console.WriteLine("Error getting key file..."); return; } InputForm inForm = new InputForm(); inForm.Text = "Enter username@hostname"; inForm.textBox1.Text = Environment.UserName+"@localhost"; if (inForm.PromptForInput()) { String host = inForm.textBox1.Text; String user=host.Substring(0, host.IndexOf('@')); host=host.Substring(host.IndexOf('@')+1); Session session=jsch.getSession(user, host, 22); // username and passphrase will be given via UserInfo interface. UserInfo ui=new MyUserInfo(); session.setUserInfo(ui); session.connect(); Channel channel=session.openChannel("shell"); channel.setInputStream(Console.OpenStandardInput()); channel.setOutputStream(Console.OpenStandardOutput()); channel.connect(); } inForm.Close(); } catch(Exception e) { Console.WriteLine(e); } }
public static void Main(params string[] arg) { if(arg.Length<3) { Console.Error.WriteLine( "usage: java KeyGen rsa output_keyfile comment\n"+ " java KeyGen dsa output_keyfile comment"); Environment.Exit(-1); } //Get sig type ('rsa' or 'dsa') String _type=arg[0]; int type=0; if(_type.Equals("rsa")){type=KeyPair.RSA;} else if(_type.Equals("dsa")){type=KeyPair.DSA;} else { Console.Error.WriteLine( "usage: java KeyGen rsa output_keyfile comment\n"+ " java KeyGen dsa output_keyfile comment"); Environment.Exit(-1); } //Output file name String filename=arg[1]; //Signature comment String comment=arg[2]; //Create a new JSch instance JSch jsch=new JSch(); //Prompt the user for a passphrase for the private key file String passphrase=InputForm.GetUserInput("Enter passphrase (empty for no passphrase)", true); try { //Generate the new key pair KeyPair kpair=KeyPair.genKeyPair(jsch, type); //Set a passphrase kpair.setPassphrase(passphrase); //Write the private key to "filename" kpair.writePrivateKey(filename); //Write the public key to "filename.pub" kpair.writePublicKey(filename+".pub", comment); //Print the key fingerprint Console.WriteLine("Finger print: "+kpair.getFingerPrint()); //Free resources kpair.dispose(); } catch(Exception e) { Console.WriteLine(e); } Environment.Exit(0); }
public static KeyPair genKeyPair(JSch jsch, int type, int key_size) { KeyPair kpair=null; if(type==DSA){ kpair=new KeyPairDSA(jsch); } else if(type==RSA){ kpair=new KeyPairRSA(jsch); } if(kpair!=null) { kpair.generate(key_size); } return kpair; }
protected override JSch GetJSch(OpenSshConfig.Host hc, FS fs) { JSch.SetConfig("StrictHostKeyChecking", "no"); // automatic acceptance for known host if 'known_hosts' is missing var jsch = base.GetJSch(hc, fs); var homePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); var sshPath = homePath + @"\.ssh"; jsch.AddIdentity(sshPath + @"\id_rsa"); jsch.SetKnownHosts(sshPath + @"\known_hosts"); return(jsch); }
/// <summary> /// 实例化 SFTP 对象 /// </summary> /// <param name="ip">服务器IP</param> /// <param name="user">用户名</param> /// <param name="pwd">密码</param> /// <param name="port">端口</param> /// <param name="privateKey">私钥</param> /// <param name="passphrase">私钥口令</param> public SFTPHelper(string ip, string user, string pwd, int port = 22, string privateKey = "", string passphrase = "") { JSch jsch = new JSch(); jsch.addIdentity(privateKey, passphrase); m_session = jsch.getSession(user, ip, port); MyUserInfo ui = new MyUserInfo(); ui.setPassword(pwd); m_session.setUserInfo(ui); this.Connect(); }
public SFTPHelper(string ip, string user, string password, int port = 22) { JSch jsch = new JSch(); session = jsch.getSession(user, ip, port); session.setPassword(password); Hashtable foo = new Hashtable(); //不加会默认key登陆 foo.Add("StrictHostKeyChecking", "no"); session.setConfig(foo); }
private JSch getDefaultJSch() { if (_defaultJSch == null) { _defaultJSch = createDefaultJSch(); foreach (object name in _defaultJSch.getIdentityNames()) { _byIdentityFile.put((string)name, _defaultJSch); } } return(_defaultJSch); }
/// <summary> /// 构造函数 /// </summary> /// <param name="ip">sftp地址</param> /// <param name="user">sftp用户名</param> /// <param name="pwd">sftp密码</param> /// <param name="port">端口,默认20</param> public SftpHelper(string ip, string user, string pwd, string port = "20") { int serverport = Int32.Parse(port); JSch jsch = new JSch(); m_session = jsch.getSession(user, ip, serverport); MyUserInfo ui = new MyUserInfo(); ui.setPassword(pwd); m_session.setUserInfo(ui); }
private static void LoadIdentity(JSch sch, FilePath priv) { if (priv.IsFile()) { try { sch.AddIdentity(priv.GetAbsolutePath()); } catch (JSchException) { } } }
public static void RunExample(String[] arg) { int port; try { //Create a new JSch instance JSch jsch = new JSch(); //Prompt for username and server host Console.WriteLine("Please enter the user and host info at the popup window..."); String host = InputForm.GetUserInput ("Enter username@hostname", Environment.UserName + "@localhost"); String user = host.Substring(0, host.IndexOf('@')); host = host.Substring(host.IndexOf('@') + 1); //Create a new SSH session Session session = jsch.getSession(user, host, 22); // username and password will be given via UserInfo interface. UserInfo ui = new MyUserInfo(); session.setUserInfo(ui); session.connect(); //Get from user the remote host and remote host port String foo = InputForm.GetUserInput("Enter host and port", "host:port"); host = foo.Substring(0, foo.IndexOf(':')); port = int.Parse(foo.Substring(foo.IndexOf(':') + 1)); Console.WriteLine("System.{in,out} will be forwarded to " + host + ":" + port + "."); Channel channel = session.openChannel("direct-tcpip"); ((ChannelDirectTCPIP)channel).setInputStream(Console.OpenStandardInput()); ((ChannelDirectTCPIP)channel).setOutputStream(Console.OpenStandardOutput()); ((ChannelDirectTCPIP)channel).setHost(host); ((ChannelDirectTCPIP)channel).setPort(port); channel.connect(); while (!channel.isClosed()) { System.Threading.Thread.Sleep(500); } channel.disconnect(); session.disconnect(); } catch (Exception e) { Console.WriteLine(e); } }
public static void Main(String[] arg) { int port; try { //Create a new JSch instance JSch jsch=new JSch(); //Prompt for username and server host Console.WriteLine("Please enter the user and host info at the popup window..."); String host = InputForm.GetUserInput ("Enter username@hostname", Environment.UserName+"@localhost"); String user=host.Substring(0, host.IndexOf('@')); host=host.Substring(host.IndexOf('@')+1); //Create a new SSH session Session session=jsch.getSession(user, host, 22); // username and password will be given via UserInfo interface. UserInfo ui=new MyUserInfo(); session.setUserInfo(ui); session.connect(); //Get from user the remote host and remote host port String foo = InputForm.GetUserInput("Enter host and port", "host:port"); host=foo.Substring(0, foo.IndexOf(':')); port=int.Parse(foo.Substring(foo.IndexOf(':')+1)); Console.WriteLine("System.{in,out} will be forwarded to "+ host+":"+port+"."); Channel channel=session.openChannel("direct-tcpip"); ((ChannelDirectTCPIP)channel).setInputStream(Console.OpenStandardInput()); ((ChannelDirectTCPIP)channel).setOutputStream(Console.OpenStandardOutput()); ((ChannelDirectTCPIP)channel).setHost(host); ((ChannelDirectTCPIP)channel).setPort(port); channel.connect(); while(!channel.isClosed()) { System.Threading.Thread.Sleep(500); } channel.disconnect(); session.disconnect(); } catch(Exception e) { Console.WriteLine(e); } }
public static void Main(String[] arg) { //Get the private key filename from the user Console.WriteLine("Please choose your private key file..."); String pkey = InputForm.GetFileFromUser("Choose your privatekey(ex. ~/.ssh/id_dsa)"); Console.WriteLine("You chose " + pkey + "."); //Create a new JSch instance JSch jsch = new JSch(); try { //Load the key pair KeyPair kpair = KeyPair.load(jsch, pkey); //Print the key file encryption status Console.WriteLine(pkey + " has " + (kpair.isEncrypted()?"been ":"not been ") + "encrypted"); String passphrase = ""; while (kpair.isEncrypted()) { passphrase = InputForm.GetUserInput("Enter passphrase for " + pkey, true); if (!kpair.decrypt(passphrase)) { Console.WriteLine("failed to decrypt " + pkey); } else { Console.WriteLine(pkey + " is decrypted."); } } passphrase = ""; passphrase = InputForm.GetUserInput("Enter new passphrase for " + pkey + " (empty for no passphrase)", true); //Set the new passphrase kpair.setPassphrase(passphrase); //write the key to file kpair.writePrivateKey(pkey); //free the resource kpair.dispose(); } catch (Exception e) { Console.WriteLine(e); } }
private static void loadIdentity(JSch sch, FileInfo priv) { if (!File.Exists(priv.ToString())) { return; } try { sch.addIdentity(Path.GetFullPath(priv.ToString())); } catch (JSchException) { } }
public static void Main(String[] arg) { //Get the private key filename from the user Console.WriteLine("Please choose your private key file..."); String pkey = InputForm.GetFileFromUser("Choose your privatekey(ex. ~/.ssh/id_dsa)"); Console.WriteLine("You chose "+pkey+"."); //Create a new JSch instance JSch jsch=new JSch(); try { //Load the key pair KeyPair kpair=KeyPair.load(jsch, pkey); //Print the key file encryption status Console.WriteLine(pkey+" has "+(kpair.isEncrypted()?"been ":"not been ")+"encrypted"); String passphrase = ""; while(kpair.isEncrypted()) { passphrase = InputForm.GetUserInput("Enter passphrase for "+pkey, true); if(!kpair.decrypt(passphrase)) { Console.WriteLine("failed to decrypt "+pkey); } else { Console.WriteLine(pkey+" is decrypted."); } } passphrase=""; passphrase=InputForm.GetUserInput("Enter new passphrase for "+pkey+ " (empty for no passphrase)", true); //Set the new passphrase kpair.setPassphrase(passphrase); //write the key to file kpair.writePrivateKey(pkey); //free the resource kpair.dispose(); } catch(Exception e) { Console.WriteLine(e); } }
public static void Main(String[] arg) { int port; try { //Create a new JSch instance JSch jsch=new JSch(); //Prompt for username and server host Console.WriteLine("Please enter the user and host info at the popup window..."); String host = InputForm.GetUserInput ("Enter username@hostname", Environment.UserName+"@localhost"); String user=host.Substring(0, host.IndexOf('@')); host=host.Substring(host.IndexOf('@')+1); //Create a new SSH session Session session=jsch.getSession(user, host, 22); //Get from user the local port, remote host and remote host port String foo = InputForm.GetUserInput("Enter -L port:host:hostport","port:host:hostport"); int lport=int.Parse(foo.Substring(0, foo.IndexOf(':'))); foo=foo.Substring(foo.IndexOf(':')+1); String rhost=foo.Substring(0, foo.IndexOf(':')); int rport=int.Parse(foo.Substring(foo.IndexOf(':')+1)); // username and password will be given via UserInfo interface. UserInfo ui=new MyUserInfo(); session.setUserInfo(ui); session.connect(); Console.WriteLine("localhost:"+lport+" -> "+rhost+":"+rport); //Set port forwarding on the opened session session.setPortForwardingL(lport, rhost, rport); } catch(Exception e) { Console.WriteLine(e); } }
internal Session(JSch jsch) { ; this.jsch=jsch; buf=new Buffer(); packet=new Packet(buf); }
public static void Main(String[] arg) { try { JSch jsch=new JSch(); InputForm inForm = new InputForm(); inForm.Text = "Enter username@hostname"; inForm.textBox1.Text = Environment.UserName+"@localhost"; if (!inForm.PromptForInput()) { Console.WriteLine("Cancelled"); return; } String host = inForm.textBox1.Text; String user=host.Substring(0, host.IndexOf('@')); host=host.Substring(host.IndexOf('@')+1); Session session=jsch.getSession(user, host, 22); // username and password will be given via UserInfo interface. UserInfo ui=new MyUserInfo(); session.setUserInfo(ui); session.connect(); Channel channel=session.openChannel("sftp"); channel.connect(); ChannelSftp c=(ChannelSftp)channel; Stream ins=Console.OpenStandardInput(); TextWriter outs=Console.Out; ArrayList cmds=new ArrayList(); byte[] buf=new byte[1024]; int i; String str; int level=0; while(true) { outs.Write("sftp> "); cmds.Clear(); i=ins.Read(buf, 0, 1024); if(i<=0)break; i--; if(i>0 && buf[i-1]==0x0d)i--; //str=Util.getString(buf, 0, i); //Console.WriteLine("|"+str+"|"); int s=0; for(int ii=0; ii<i; ii++) { if(buf[ii]==' ') { if(ii-s>0){ cmds.Add(Util.getString(buf, s, ii-s)); } while(ii<i){if(buf[ii]!=' ')break; ii++;} s=ii; } } if(s<i){ cmds.Add(Util.getString(buf, s, i-s)); } if(cmds.Count==0)continue; String cmd=(String)cmds[0]; if(cmd.Equals("quit")) { c.quit(); break; } if(cmd.Equals("exit")) { c.exit(); break; } if(cmd.Equals("rekey")) { session.rekey(); continue; } if(cmd.Equals("compression")) { if(cmds.Count<2) { outs.WriteLine("compression level: "+level); continue; } try { level=int.Parse((String)cmds[1]); Hashtable config=new Hashtable(); if(level==0) { config.Add("compression.s2c", "none"); config.Add("compression.c2s", "none"); } else { config.Add("compression.s2c", "zlib,none"); config.Add("compression.c2s", "zlib,none"); } session.setConfig(config); } catch{}//(Exception e){} continue; } if(cmd.Equals("cd") || cmd.Equals("lcd")) { if(cmds.Count<2) continue; String path=(String)cmds[1]; try { if(cmd.Equals("cd")) c.cd(path); else c.lcd(path); } catch(SftpException e) { Console.WriteLine(e.message); } continue; } if(cmd.Equals("rm") || cmd.Equals("rmdir") || cmd.Equals("mkdir")) { if(cmds.Count<2) continue; String path=(String)cmds[1]; try { if(cmd.Equals("rm")) c.rm(path); else if(cmd.Equals("rmdir")) c.rmdir(path); else c.mkdir(path); } catch(SftpException e) { Console.WriteLine(e.message); } continue; } if(cmd.Equals("chgrp") || cmd.Equals("chown") || cmd.Equals("chmod")) { if(cmds.Count!=3) continue; String path=(String)cmds[2]; int foo=0; if(cmd.Equals("chmod")) { byte[] bar=Util.getBytes((String)cmds[1]); int k; for(int j=0; j<bar.Length; j++) { k=bar[j]; if(k<'0'||k>'7'){foo=-1; break;} foo<<=3; foo|=(k-'0'); } if(foo==-1)continue; } else { try{foo=int.Parse((String)cmds[1]);} catch{}//(Exception e){continue;} } try { if(cmd.Equals("chgrp")){ c.chgrp(foo, path); } else if(cmd.Equals("chown")){ c.chown(foo, path); } else if(cmd.Equals("chmod")){ c.chmod(foo, path); } } catch(SftpException e) { Console.WriteLine(e.message); } continue; } if(cmd.Equals("pwd") || cmd.Equals("lpwd")) { str=(cmd.Equals("pwd")?"Remote":"Local"); str+=" working directory: "; if(cmd.Equals("pwd")) str+=c.pwd(); else str+=c.lpwd(); outs.WriteLine(str); continue; } if(cmd.Equals("ls") || cmd.Equals("dir")) { String path="."; if(cmds.Count==2) path=(String)cmds[1]; try { ArrayList vv=c.ls(path); if(vv!=null) { for(int ii=0; ii<vv.Count; ii++) { object obj = vv[ii]; if(obj is ChannelSftp.LsEntry) outs.WriteLine(vv[ii]); } } } catch(SftpException e) { Console.WriteLine(e.message); } continue; } if(cmd.Equals("lls") || cmd.Equals("ldir")) { String path="."; if(cmds.Count==2) path=(String)cmds[1]; try { //java.io.File file=new java.io.File(path); if(!File.Exists(path)) { outs.WriteLine(path+": No such file or directory"); continue; } if(Directory.Exists(path)) { String[] list=Directory.GetDirectories(path); for(int ii=0; ii<list.Length; ii++) { outs.WriteLine(list[ii]); } continue; } outs.WriteLine(path); } catch(Exception e) { Console.WriteLine(e); } continue; } if(cmd.Equals("get") || cmd.Equals("get-resume") || cmd.Equals("get-append") || cmd.Equals("put") || cmd.Equals("put-resume") || cmd.Equals("put-append") ) { if(cmds.Count!=2 && cmds.Count!=3) continue; String p1=(String)cmds[1]; // String p2=p1; String p2="."; if(cmds.Count==3)p2=(String)cmds[2]; try { SftpProgressMonitor monitor=new MyProgressMonitor(); if(cmd.StartsWith("get")) { int mode=ChannelSftp.OVERWRITE; if(cmd.Equals("get-resume")){ mode=ChannelSftp.RESUME; } else if(cmd.Equals("get-append")){ mode=ChannelSftp.APPEND; } c.get(p1, p2, monitor, mode); } else { int mode=ChannelSftp.OVERWRITE; if(cmd.Equals("put-resume")){ mode=ChannelSftp.RESUME; } else if(cmd.Equals("put-append")){ mode=ChannelSftp.APPEND; } c.put(p1, p2, monitor, mode); } } catch(SftpException e) { Console.WriteLine(e.message); } continue; } if(cmd.Equals("ln") || cmd.Equals("symlink") || cmd.Equals("rename")) { if(cmds.Count!=3) continue; String p1=(String)cmds[1]; String p2=(String)cmds[2]; try { if(cmd.Equals("rename")) c.rename(p1, p2); else c.symlink(p1, p2); } catch(SftpException e) { Console.WriteLine(e.message); } continue; } if(cmd.Equals("stat") || cmd.Equals("lstat")) { if(cmds.Count!=2) continue; String p1=(String)cmds[1]; SftpATTRS attrs=null; try { if(cmd.Equals("stat")) attrs=c.stat(p1); else attrs=c.lstat(p1); } catch(SftpException e) { Console.WriteLine(e.message); } if(attrs!=null) { outs.WriteLine(attrs); } else { } continue; } if(cmd.Equals("version")) { outs.WriteLine("SFTP protocol version "+c.version()); continue; } if(cmd.Equals("help") || cmd.Equals("?")) { outs.WriteLine(help); continue; } outs.WriteLine("unimplemented command: "+cmd); } session.disconnect(); } catch(Exception e) { Console.WriteLine(e); } }
internal IdentityFile(String identity, JSch jsch) { this.identity=identity; this.jsch=jsch; try { Type c=Type.GetType(jsch.getConfig("3des-cbc")); cipher=(Cipher)Activator.CreateInstance(c); key=new byte[cipher.getBlockSize()]; // 24 iv=new byte[cipher.getIVSize()]; // 8 c=Type.GetType(jsch.getConfig("md5")); hash=(HASH)(Activator.CreateInstance(c)); hash.init(); FileInfo file=new FileInfo(identity); FileStream fis = File.OpenRead(identity); byte[] buf=new byte[(int)(file.Length)]; int len=fis.Read(buf, 0, buf.Length); fis.Close(); int i=0; while(i<len) { if(buf[i]=='B'&& buf[i+1]=='E'&& buf[i+2]=='G'&& buf[i+3]=='I') { i+=6; if(buf[i]=='D'&& buf[i+1]=='S'&& buf[i+2]=='A'){ type=DSS; } else if(buf[i]=='R'&& buf[i+1]=='S'&& buf[i+2]=='A'){ type=RSA; } else if(buf[i]=='S'&& buf[i+1]=='S'&& buf[i+2]=='H') { // FSecure type=UNKNOWN; keytype=FSECURE; } else { //System.out.println("invalid format: "+identity); throw new JSchException("invaid privatekey: "+identity); } i+=3; continue; } if(buf[i]=='C'&& buf[i+1]=='B'&& buf[i+2]=='C'&& buf[i+3]==',') { i+=4; for(int ii=0; ii<iv.Length; ii++) { iv[ii]=(byte)(((a2b(buf[i++])<<4)&0xf0)+ (a2b(buf[i++])&0xf)); } continue; } if(buf[i]==0x0d && i+1<buf.Length && buf[i+1]==0x0a) { i++; continue; } if(buf[i]==0x0a && i+1<buf.Length) { if(buf[i+1]==0x0a){ i+=2; break; } if(buf[i+1]==0x0d && i+2<buf.Length && buf[i+2]==0x0a) { i+=3; break; } bool inheader=false; for(int j=i+1; j<buf.Length; j++) { if(buf[j]==0x0a) break; //if(buf[j]==0x0d) break; if(buf[j]==':'){inheader=true; break;} } if(!inheader) { i++; encrypted=false; // no passphrase break; } } i++; } if(type==ERROR) { throw new JSchException("invaid privatekey: "+identity); } int start=i; while(i<len) { if(buf[i]==0x0a) { bool xd=(buf[i-1]==0x0d); Array.Copy(buf, i+1, buf, i-(xd ? 1 : 0), len-i-1-(xd ? 1 : 0) ); if(xd)len--; len--; continue; } if(buf[i]=='-'){ break; } i++; } encoded_data=Util.fromBase64(buf, start, i-start); if(encoded_data.Length>4 && // FSecure encoded_data[0]==(byte)0x3f && encoded_data[1]==(byte)0x6f && encoded_data[2]==(byte)0xf9 && encoded_data[3]==(byte)0xeb) { Buffer _buf=new Buffer(encoded_data); _buf.getInt(); // 0x3f6ff9be _buf.getInt(); byte[]_type=_buf.getString(); //System.out.println("type: "+new String(_type)); byte[] _cipher=_buf.getString(); String s_cipher=System.Text.Encoding.Default.GetString(_cipher); //System.out.println("cipher: "+cipher); if(s_cipher.Equals("3des-cbc")) { _buf.getInt(); byte[] foo=new byte[encoded_data.Length-_buf.getOffSet()]; _buf.getByte(foo); encoded_data=foo; encrypted=true; throw new JSchException("unknown privatekey format: "+identity); } else if(s_cipher.Equals("none")) { _buf.getInt(); //_buf.getInt(); encrypted=false; byte[] foo=new byte[encoded_data.Length-_buf.getOffSet()]; _buf.getByte(foo); encoded_data=foo; } } try { file=new FileInfo(identity+".pub"); fis=File.OpenRead(identity+".pub"); buf=new byte[(int)(file.Length)]; len=fis.Read(buf, 0, buf.Length); fis.Close(); } catch { return; } if(buf.Length>4 && // FSecure's public key buf[0]=='-' && buf[1]=='-' && buf[2]=='-' && buf[3]=='-') { i=0; do{i++;}while(buf.Length>i && buf[i]!=0x0a); if(buf.Length<=i) return; while(true) { if(buf[i]==0x0a) { bool inheader=false; for(int j=i+1; j<buf.Length; j++) { if(buf[j]==0x0a) break; if(buf[j]==':'){inheader=true; break;} } if(!inheader) { i++; break; } } i++; } if(buf.Length<=i) return; start=i; while(i<len) { if(buf[i]==0x0a) { Array.Copy(buf, i+1, buf, i, len-i-1); len--; continue; } if(buf[i]=='-'){ break; } i++; } publickeyblob=Util.fromBase64(buf, start, i-start); if(type==UNKNOWN) { if(publickeyblob[8]=='d') { type=DSS; } else if(publickeyblob[8]=='r') { type=RSA; } } } else { if(buf[0]!='s'|| buf[1]!='s'|| buf[2]!='h'|| buf[3]!='-') return; i=0; while(i<len){ if(buf[i]==' ')break; i++;} i++; if(i>=len) return; start=i; while(i<len){ if(buf[i]==' ')break; i++;} publickeyblob=Util.fromBase64(buf, start, i-start); } } catch(Exception e) { Console.WriteLine("Identity: "+e); if(e is JSchException) throw (JSchException)e; throw new JSchException(e.ToString()); } }
private byte[] q_array; // prime q #endregion Fields #region Constructors public KeyPairRSA(JSch jsch) : base(jsch) { }
internal KnownHosts(JSch jsch) : base() { this.jsch=jsch; pool=new System.Collections.ArrayList(); }
public static void RunExample(String[] arg) { if(arg.Length!=1) { Console.WriteLine("usage: java ChangePassphrase private_key"); Environment.Exit(-1); } JSch jsch=new JSch(); String pkey=arg[0]; try { KeyPair kpair=KeyPair.load(jsch, pkey); Console.WriteLine(pkey+" has "+(kpair.isEncrypted()?"been ":"not been ")+"encrypted"); String passphrase=""; InputForm passphraseField = null; while(kpair.isEncrypted()) { passphraseField=new InputForm(); passphraseField.PasswordField = true; if(!passphraseField.PromptForInput()) { Environment.Exit(-1); } passphrase=passphraseField.getText(); if(!kpair.decrypt(passphrase)) { Console.WriteLine("failed to decrypt "+pkey); } else { Console.WriteLine(pkey+" is decrypted."); } } passphrase=""; passphraseField=new InputForm(); passphraseField.PasswordField = true; if(!passphraseField.PromptForInput()) { Environment.Exit(-1); } passphrase=passphraseField.getText(); kpair.setPassphrase(passphrase); kpair.writePrivateKey(pkey); kpair.dispose(); } catch(Exception e) { Console.WriteLine(e); } Environment.Exit(0); }
public static void RunExample(String[] arg) { try { JSch jsch=new JSch(); OpenFileDialog chooser = new OpenFileDialog(); chooser.Title = "Choose your known_hosts(ex. ~/.ssh/known_hosts)"; //chooser.setFileHidingEnabled(false); DialogResult returnVal = chooser.ShowDialog(); if(returnVal == DialogResult.OK) { Console.WriteLine("You chose "+ chooser.FileName+"."); jsch.setKnownHosts(chooser.FileName); } else { Console.WriteLine("Error getting host file..."); return; } HostKeyRepository hkr=jsch.getHostKeyRepository(); HostKey[] hks=hkr.getHostKey(); if(hks!=null) { Console.WriteLine("Host keys in "+hkr.getKnownHostsRepositoryID()); for(int i=0; i<hks.Length; i++) { HostKey hk=hks[i]; Console.WriteLine(hk.getHost()+" "+ hk.getType()+" "+ hk.getFingerPrint(jsch)); } Console.WriteLine(""); } InputForm inForm = new InputForm(); inForm.Text = "Enter username@hostname"; inForm.textBox1.Text = Environment.UserName+"@localhost"; if (inForm.PromptForInput()) { String host = inForm.textBox1.Text; String user=host.Substring(0, host.IndexOf('@')); host=host.Substring(host.IndexOf('@')+1); Session session=jsch.getSession(user, host, 22); // username and password will be given via UserInfo interface. UserInfo ui=new MyUserInfo(); session.setUserInfo(ui); session.connect(); HostKey hk=session.getHostKey(); Console.WriteLine("HostKey: "+ hk.getHost()+" "+ hk.getType()+" "+ hk.getFingerPrint(jsch)); Channel channel=session.openChannel("shell"); channel.setInputStream(Console.OpenStandardInput()); channel.setOutputStream(Console.OpenStandardOutput()); channel.connect(); } inForm.Close(); } catch(Exception e) { Console.WriteLine(e); } }
public static void Main(String[] arg) { if(arg.Length!=2) { Console.WriteLine("usage: java ScpTo file1 user@remotehost:file2"); Environment.Exit(-1); } try { String lfile=arg[0]; String user=arg[1].Substring(0, arg[1].IndexOf('@')); arg[1]=arg[1].Substring(arg[1].IndexOf('@')+1); String host=arg[1].Substring(0, arg[1].IndexOf(':')); String rfile=arg[1].Substring(arg[1].IndexOf(':')+1); JSch jsch=new JSch(); Session session=jsch.getSession(user, host, 22); // username and password will be given via UserInfo interface. UserInfo ui=new MyUserInfo(); session.setUserInfo(ui); session.connect(); // exec 'scp -t rfile' remotely String command="scp -p -t "+rfile; Channel channel=session.openChannel("exec"); ((ChannelExec)channel).setCommand(command); // get I/O streams for remote scp Stream outs=channel.getOutputStream(); Stream ins=channel.getInputStream(); channel.connect(); byte[] tmp=new byte[1]; if(checkAck(ins)!=0) { Environment.Exit(0); } // send "C0644 filesize filename", where filename should not include '/' int filesize=(int)(new FileInfo(lfile)).Length; command="C0644 "+filesize+" "; if(lfile.LastIndexOf('/')>0) { command+=lfile.Substring(lfile.LastIndexOf('/')+1); } else { command+=lfile; } command+="\n"; byte[] buff = Util.getBytes(command); outs.Write(buff, 0, buff.Length); outs.Flush(); if(checkAck(ins)!=0) { Environment.Exit(0); } // send a content of lfile FileStream fis=File.OpenRead(lfile); byte[] buf=new byte[1024]; while(true) { int len=fis.Read(buf, 0, buf.Length); if(len<=0) break; outs.Write(buf, 0, len); outs.Flush(); Console.Write("#"); } // send '\0' buf[0]=0; outs.Write(buf, 0, 1); outs.Flush(); Console.Write("."); if(checkAck(ins)!=0) { Environment.Exit(0); } Console.WriteLine("OK"); Environment.Exit(0); } catch(Exception e) { Console.WriteLine(e); } }
public static void Main(String[] arg) { try { //Get the "known hosts" filename from the user Console.WriteLine("Please select your 'known_hosts' from the poup window..."); String file = InputForm.GetFileFromUser("Choose your known_hosts(ex. ~/.ssh/known_hosts)"); Console.WriteLine("You chose "+file+"."); //Create a new JSch instance JSch jsch=new JSch(); //Set the known hosts file jsch.setKnownHosts(file); //Get the KnownHosts repository from JSchs HostKeyRepository hkr=jsch.getHostKeyRepository(); //Print all known hosts and keys HostKey[] hks=hkr.getHostKey(); HostKey hk; if(hks!=null) { Console.WriteLine(); Console.WriteLine("Host keys in "+hkr.getKnownHostsRepositoryID()+":"); for(int i=0; i<hks.Length; i++) { hk=hks[i]; Console.WriteLine(hk.getHost()+" "+ hk.getType()+" "+ hk.getFingerPrint(jsch)); } Console.WriteLine(""); } //Now connect to the remote server... //Prompt for username and server host Console.WriteLine("Please enter the user and host info at the popup window..."); String host = InputForm.GetUserInput ("Enter username@hostname", Environment.UserName+"@localhost"); String user=host.Substring(0, host.IndexOf('@')); host=host.Substring(host.IndexOf('@')+1); //Create a new SSH session Session session=jsch.getSession(user, host, 22); // username and password will be given via UserInfo interface. UserInfo ui=new MyUserInfo(); session.setUserInfo(ui); //Connect to remote SSH server session.connect(); //Print the host key info //of the connected server: hk=session.getHostKey(); Console.WriteLine("HostKey: "+ hk.getHost()+" "+ hk.getType()+" "+ hk.getFingerPrint(jsch)); //Open a new Shell channel on the SSH session Channel channel=session.openChannel("shell"); //Redirect standard I/O to the SSH channel channel.setInputStream(Console.OpenStandardInput()); channel.setOutputStream(Console.OpenStandardOutput()); //Connect the channel channel.connect(); Console.WriteLine("-- Shell channel is connected using the {0} cipher", session.getCipher()); //Wait till channel is closed while(!channel.isClosed()) { System.Threading.Thread.Sleep(500); } //Disconnect from remote server channel.disconnect(); session.disconnect(); } catch(Exception e) { Console.WriteLine(e); } }
public static void Main(String[] arg) { if(arg.Length!=2) { Console.WriteLine("usage: java ScpFrom user@remotehost:file1 file2"); return; } try { String user=arg[0].Substring(0, arg[0].IndexOf('@')); arg[0]=arg[0].Substring(arg[0].IndexOf('@')+1); String host=arg[0].Substring(0, arg[0].IndexOf(':')); String rfile=arg[0].Substring(arg[0].IndexOf(':')+1); String lfile=arg[1]; String prefix=null; if(Directory.Exists(lfile)) { prefix=lfile+Path.DirectorySeparatorChar; } JSch jsch=new JSch(); Session session=jsch.getSession(user, host, 22); // username and password will be given via UserInfo interface. UserInfo ui=new MyUserInfo(); session.setUserInfo(ui); session.connect(); // exec 'scp -f rfile' remotely String command="scp -f "+rfile; Channel channel=session.openChannel("exec"); ((ChannelExec)channel).setCommand(command); // get I/O streams for remote scp Stream outs=channel.getOutputStream(); Stream ins=channel.getInputStream(); channel.connect(); byte[] buf=new byte[1024]; // send '\0' buf[0]=0; outs.Write(buf, 0, 1); outs.Flush(); while(true) { int c=checkAck(ins); if(c!='C') { break; } // read '0644 ' ins.Read(buf, 0, 5); int filesize=0; while(true) { ins.Read(buf, 0, 1); if(buf[0]==' ')break; filesize=filesize*10+(buf[0]-'0'); } String file=null; for(int i=0;;i++) { ins.Read(buf, i, 1); if(buf[i]==(byte)0x0a) { file=Util.getString(buf, 0, i); break; } } //Console.WriteLine("filesize="+filesize+", file="+file); // send '\0' buf[0]=0; outs.Write(buf, 0, 1); outs.Flush(); // read a content of lfile FileStream fos=File.OpenWrite(prefix==null ? lfile : prefix+file); int foo; while(true) { if(buf.Length<filesize) foo=buf.Length; else foo=filesize; ins.Read(buf, 0, foo); fos.Write(buf, 0, foo); filesize-=foo; if(filesize==0) break; } fos.Close(); byte[] tmp=new byte[1]; if(checkAck(ins)!=0) { Environment.Exit(0); } // send '\0' buf[0]=0; outs.Write(buf, 0, 1); outs.Flush(); } Environment.Exit(0); } catch(Exception e) { Console.WriteLine(e); } }
public static KeyPair load(JSch jsch, String prvkey, String pubkey) { byte[] iv=new byte[8]; // 8 bool encrypted=true; byte[] data=null; byte[] publickeyblob=null; int type=ERROR; int vendor=VENDOR_OPENSSH; try { //File file=new File(prvkey); FileStream fis=File.OpenRead(prvkey); byte[] buf=new byte[(int)(fis.Length)]; int len=fis.Read(buf, 0, buf.Length); fis.Close(); int i=0; while(i<len) { if(buf[i]=='B'&& buf[i+1]=='E'&& buf[i+2]=='G'&& buf[i+3]=='I') { i+=6; if(buf[i]=='D'&& buf[i+1]=='S'&& buf[i+2]=='A'){ type=DSA; } else if(buf[i]=='R'&& buf[i+1]=='S'&& buf[i+2]=='A'){ type=RSA; } else if(buf[i]=='S'&& buf[i+1]=='S'&& buf[i+2]=='H') { // FSecure type=UNKNOWN; vendor=VENDOR_FSECURE; } else { //System.outs.println("invalid format: "+identity); throw new JSchException("invaid privatekey: "+prvkey); } i+=3; continue; } if(buf[i]=='C'&& buf[i+1]=='B'&& buf[i+2]=='C'&& buf[i+3]==',') { i+=4; for(int ii=0; ii<iv.Length; ii++) { iv[ii]=(byte)(((a2b(buf[i++])<<4)&0xf0)+(a2b(buf[i++])&0xf)); } continue; } if(buf[i]==0x0d && i+1<buf.Length && buf[i+1]==0x0a) { i++; continue; } if(buf[i]==0x0a && i+1<buf.Length) { if(buf[i+1]==0x0a){ i+=2; break; } if(buf[i+1]==0x0d && i+2<buf.Length && buf[i+2]==0x0a) { i+=3; break; } bool inheader=false; for(int j=i+1; j<buf.Length; j++) { if(buf[j]==0x0a) break; //if(buf[j]==0x0d) break; if(buf[j]==':'){inheader=true; break;} } if(!inheader) { i++; encrypted=false; // no passphrase break; } } i++; } if(type==ERROR) { throw new JSchException("invaid privatekey: "+prvkey); } int start=i; while(i<len) { if(buf[i]==0x0a) { bool xd=(buf[i-1]==0x0d); Array.Copy(buf, i+1, buf, i-(xd ? 1 : 0), len-i-1-(xd ? 1 : 0) ); if(xd)len--; len--; continue; } if(buf[i]=='-'){ break; } i++; } data=Util.fromBase64(buf, start, i-start); if(data.Length>4 && // FSecure data[0]==(byte)0x3f && data[1]==(byte)0x6f && data[2]==(byte)0xf9 && data[3]==(byte)0xeb) { Buffer _buf=new Buffer(data); _buf.getInt(); // 0x3f6ff9be _buf.getInt(); byte[]_type=_buf.getString(); //System.outs.println("type: "+new String(_type)); byte[] _cipher=_buf.getString(); String cipher=Util.getString(_cipher); //System.outs.println("cipher: "+cipher); if(cipher.Equals("3des-cbc")) { _buf.getInt(); byte[] foo=new byte[data.Length-_buf.getOffSet()]; _buf.getByte(foo); data=foo; encrypted=true; throw new JSchException("unknown privatekey format: "+prvkey); } else if(cipher.Equals("none")) { _buf.getInt(); _buf.getInt(); encrypted=false; byte[] foo=new byte[data.Length-_buf.getOffSet()]; _buf.getByte(foo); data=foo; } } if(pubkey!=null) { try { //file=new File(pubkey); fis=File.OpenRead(pubkey); buf=new byte[(int)(fis.Length)]; len=fis.Read(buf, 0, buf.Length); fis.Close(); if(buf.Length>4 && // FSecure's public key buf[0]=='-' && buf[1]=='-' && buf[2]=='-' && buf[3]=='-') { bool valid=true; i=0; do{i++;}while(buf.Length>i && buf[i]!=0x0a); if(buf.Length<=i) {valid=false;} while(valid) { if(buf[i]==0x0a) { bool inheader=false; for(int j=i+1; j<buf.Length; j++) { if(buf[j]==0x0a) break; if(buf[j]==':'){inheader=true; break;} } if(!inheader) { i++; break; } } i++; } if(buf.Length<=i){valid=false;} start=i; while(valid && i<len) { if(buf[i]==0x0a) { Array.Copy(buf, i+1, buf, i, len-i-1); len--; continue; } if(buf[i]=='-'){ break; } i++; } if(valid) { publickeyblob=Util.fromBase64(buf, start, i-start); if(type==UNKNOWN) { if(publickeyblob[8]=='d'){ type=DSA; } else if(publickeyblob[8]=='r'){ type=RSA; } } } } else { if(buf[0]=='s'&& buf[1]=='s'&& buf[2]=='h' && buf[3]=='-') { i=0; while(i<len){ if(buf[i]==' ')break; i++;} i++; if(i<len) { start=i; while(i<len){ if(buf[i]==' ')break; i++;} publickeyblob=Util.fromBase64(buf, start, i-start); } } } } catch//(Exception ee) { } } } catch(Exception e) { if(e is JSchException) throw (JSchException)e; throw new JSchException(e.ToString()); } KeyPair kpair=null; if(type==DSA){ kpair=new KeyPairDSA(jsch); } else if(type==RSA){ kpair=new KeyPairRSA(jsch); } if(kpair!=null) { kpair.encrypted=encrypted; kpair.publickeyblob=publickeyblob; kpair.vendor=vendor; if(encrypted) { kpair.iv=iv; kpair.data=data; } else { if(kpair.parse(data)) { return kpair; } else { throw new JSchException("invaid privatekey: "+prvkey); } } } return kpair; }
public static KeyPair load(JSch jsch, String prvkey) { String pubkey=prvkey+".pub"; // if(!new File(pubkey).exists()) if(!File.Exists(pubkey)) { pubkey=null; } return load(jsch, prvkey, pubkey); }
public KeyPair(JSch jsch) { this.jsch=jsch; }
public static KeyPair genKeyPair(JSch jsch, int type) { return genKeyPair(jsch, type, 1024); }