/// <summary> /// Obtain the JSch used to create new sessions. /// </summary> /// <param name="hc">host configuration</param> /// <returns>the JSch instance to use.</returns> protected JSch getJSch(OpenSshConfig.Host hc) { if (hc == null) { throw new System.ArgumentNullException("hc"); } JSch def = getDefaultJSch(); FileInfo identityFile = hc.getIdentityFile(); if (identityFile == null) { return(def); } string identityKey = identityFile.FullName; JSch jsch = _byIdentityFile[identityKey]; if (jsch == null) { jsch = new JSch(); jsch.setHostKeyRepository(def.getHostKeyRepository()); jsch.addIdentity(identityKey); _byIdentityFile.Add(identityKey, jsch); } return(jsch); }
protected virtual void ConnectSession(int tcpPort) { m_session = m_jsch.getSession(m_user, m_host, tcpPort); if (Password != null) { if (m_userInfo == null) { m_userInfo = new DisconnectedKeyboardInteractiveUserInfo(Password); } else { throw new InvalidDataException("Cannot combine a predefined 'UserInfo' object with a predefined 'Password' value."); } } m_session.setUserInfo(m_userInfo); //determine how strict to be on host key issues. Hashtable config = new Hashtable(); switch (m_checkType) { case HostKeyCheckType.AskUser: config.Add("StrictHostKeyChecking", "ask"); break; case HostKeyCheckType.ForceMatch: config.Add("StrictHostKeyChecking", "yes"); break; case HostKeyCheckType.NoCheck: config.Add("StrictHostKeyChecking", "no"); break; default: throw new InvalidDataException("Unknown value provided for 'm_checkType' property"); } m_session.setConfig(config); if (m_hostKeyFileName != null) { m_jsch.getHostKeyRepository().setKnownHosts(m_hostKeyFileName); } m_session.connect(); }
protected JSch getJSch(OpenSshConfig.Host hc) { JSch def = getDefaultJSch(); FileInfo identityFile = hc.getIdentityFile(); if (identityFile == null) { return(def); } string identityKey = Path.GetFullPath(identityFile.ToString()); JSch jsch = byIdentityFile[identityKey]; if (jsch == null) { jsch = new JSch(); jsch.setHostKeyRepository(def.getHostKeyRepository()); jsch.addIdentity(identityKey); byIdentityFile.Add(identityKey, jsch); } return(jsch); }
//public virtual string SocketStream(string xmlRequestFilePath, string xmlResponseDestinationDirectory, Dictionary<string, string> config) //{ // var url = config["onlineBatchUrl"]; // var port = int.Parse(config["onlineBatchPort"]); // TcpClient tcpClient; // SslStream sslStream; // try // { // tcpClient = new TcpClient(url, port); // sslStream = new SslStream(tcpClient.GetStream(), false, ValidateServerCertificate, null); // } // catch (SocketException e) // { // throw new CnpOnlineException("Error establishing a network connection", e); // } // try // { // sslStream.AuthenticateAsClient(url); // } // catch (AuthenticationException e) // { // tcpClient.Close(); // throw new CnpOnlineException("Error establishing a network connection - SSL Authencation failed", e); // } // if ("true".Equals(config["printxml"])) // { // Console.WriteLine("Using XML File: " + xmlRequestFilePath); // } // using (var readFileStream = new FileStream(xmlRequestFilePath, FileMode.Open)) // { // var bytesRead = -1; // do // { // var byteBuffer = new byte[1024 * sizeof(char)]; // bytesRead = readFileStream.Read(byteBuffer, 0, byteBuffer.Length); // sslStream.Write(byteBuffer, 0, bytesRead); // sslStream.Flush(); // } while (bytesRead != 0); // } // var batchName = Path.GetFileName(xmlRequestFilePath); // var destinationDirectory = Path.GetDirectoryName(xmlResponseDestinationDirectory); // if (!Directory.Exists(destinationDirectory)) // { // if (destinationDirectory != null) Directory.CreateDirectory(destinationDirectory); // } // if ("true".Equals(config["printxml"])) // { // Console.WriteLine("Writing to XML File: " + xmlResponseDestinationDirectory + batchName); // } // using (var writeFileStream = new FileStream(xmlResponseDestinationDirectory + batchName, FileMode.Create)) // { // int bytesRead; // do // { // var byteBuffer = new byte[1024 * sizeof(char)]; // bytesRead = sslStream.Read(byteBuffer, 0, byteBuffer.Length); // writeFileStream.Write(byteBuffer, 0, bytesRead); // } while (bytesRead > 0); // } // tcpClient.Close(); // sslStream.Close(); // return xmlResponseDestinationDirectory + batchName; //} public virtual void FtpDropOff(string fileDirectory, string fileName, Dictionary <string, string> config) { ChannelSftp channelSftp; var url = config["sftpUrl"]; var username = config["sftpUsername"]; var password = config["sftpPassword"]; var knownHostsFile = config["knownHostsFile"]; var filePath = Path.Combine(fileDirectory, fileName); var printxml = config["printxml"] == "true"; if (printxml) { Console.WriteLine("Sftp Url: " + url); Console.WriteLine("Username: "******"Password: "******"Known hosts file path: " + knownHostsFile); } var jsch = new JSch(); if (printxml) { // grab the contents fo the knownhosts file and print var hostFile = File.ReadAllText(knownHostsFile); Console.WriteLine("known host contents: " + hostFile); } jsch.setKnownHosts(knownHostsFile); // setup for diagnostic // Get the KnownHosts repository from JSchs var hkr = jsch.getHostKeyRepository(); var hks = hkr.getHostKey(); HostKey hk; if (printxml) { // Print all knownhosts and keys if (hks != null) { Console.WriteLine(); Console.WriteLine("Host keys in " + hkr.getKnownHostsRepositoryID() + ":"); foreach (var t in hks) { hk = t; Console.WriteLine("local HostKey host: <" + hk.getHost() + "> type: <" + hk.getType() + "> fingerprint: <" + hk.getFingerPrint(jsch) + ">"); } Console.WriteLine(""); } } var session = jsch.getSession(username, url); session.setPassword(password); try { session.connect(); // more diagnostic code for troubleshooting sFTP connection errors if (printxml) { // Print the host key info of the connected server: hk = session.getHostKey(); Console.WriteLine("remote HostKey host: <" + hk.getHost() + "> type: <" + hk.getType() + "> fingerprint: <" + hk.getFingerPrint(jsch) + ">"); } var channel = session.openChannel("sftp"); channel.connect(); channelSftp = (ChannelSftp)channel; } catch (SftpException e) { throw new CnpOnlineException("Error occured while establishing an SFTP connection", e); } catch (JSchException e) { throw new CnpOnlineException("Error occured while attempting to establish an SFTP connection", e); } try { if (printxml) { Console.WriteLine("Dropping off local file " + filePath + " to inbound/" + fileName + ".prg"); } channelSftp.put(filePath, "inbound/" + fileName + ".prg", ChannelSftp.OVERWRITE); if (printxml) { Console.WriteLine("File copied - renaming from inbound/" + fileName + ".prg to inbound/" + fileName + ".asc"); } channelSftp.rename("inbound/" + fileName + ".prg", "inbound/" + fileName + ".asc"); } catch (SftpException e) { throw new CnpOnlineException("Error occured while attempting to upload and save the file to SFTP", e); } channelSftp.quit(); session.disconnect(); }
public static void RunExample(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 var hkr = jsch.getHostKeyRepository(); hkr.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.Message); } }
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 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); } }