void StartToUpload() { try { mScp = new Scp(mServerIP, mUsername, mPassword); mScp.OnTransferStart += SshCp_OnTransferStart; mScp.OnTransferProgress += SshCp_OnTransferProgress; mScp.OnTransferEnd += SshCp_OnTransferEnd; mScp.Connect(); if (Directory.Exists(mSrcFolder)) { mScp.Recursive = true; mFileCount = GetFileCount(mSrcFolder); } else { mScp.Recursive = false; mFileCount = 1; } mScp.To(mSrcFolder, mDesFolder); } catch (System.Exception e) { Debug.LogError("Start scp exception : " + e.Message); Reset(); } }
public Transfer(RaspberryPi pi, string local, string remote) { this.pi = pi; this.local = local; this.remote = remote; this.transferScp = new Scp(pi.getHostname(), pi.getUser(), pi.getPassword()); }
public void download(String serverPath, String localPath) { myScp = new Scp(ftpAdr, user, password); myScp.Connect(22); myScp.Get(serverPath, localPath); myScp.Close(); }
private void ApplyButton_Click(object sender, EventArgs e) { if (DefaultIP.Text == "" || DefaultGW.Text == "" || DefaultSN.Text == "" || NewIP.Text == "" || NewGW.Text == "" || NewSN.Text == "" ) { MessageBox.Show("All variables must have a value", "Error"); return; } host = DefaultIP.Text; string fileName = string.Empty; fileName = Path.GetTempFileName(); FileInfo fileInfo = new FileInfo(fileName); fileInfo.Attributes = FileAttributes.Temporary; string fullPath = Path.GetTempFileName(); StreamWriter streamWriter = File.AppendText(fullPath); streamWriter.WriteLine(Properties.Resources.rc); streamWriter.Flush(); streamWriter.Close(); //MessageBox.Show(fullPath); string local = fullPath, remote = "disk/etc/rc"; ReplaceInFile(local, "10.0.1.230", DefaultIP.Text); ReplaceInFile(local, "255.255.255.0", DefaultSN.Text); ReplaceInFile(local, "10.0.1.1", DefaultGW.Text); ReplaceInFile(local, DefaultIP.Text, NewIP.Text); ReplaceInFile(local, DefaultSN.Text, NewSN.Text); ReplaceInFile(local, DefaultGW.Text, NewGW.Text); try { Scp scp = new Scp(); scp.To(local, host, remote, user, pass); } catch { string error = "Cannot connect to controller at " + DefaultIP.Text; MessageBox.Show(error, "Error"); return; } if (File.Exists(fullPath)) { File.Delete(fullPath); } MessageBox.Show("You must reboot the controller for IP changes to take effect.", "Important"); }
private void UploadFile(string fname) { SshTransferProtocolBase sshCp = null; if (ProgramSettings.settings.SshKey.Length == 0) { sshCp = new Scp(ProgramSettings.settings.SshHost, ProgramSettings.settings.SshLogin, ProgramSettings.settings.SshPass); } else { try { sshCp = new Scp(ProgramSettings.settings.SshHost, ProgramSettings.settings.SshLogin); if (ProgramSettings.settings.SshPass.Length == 0) { sshCp.AddIdentityFile(ProgramSettings.settings.SshKey); } else { sshCp.AddIdentityFile(ProgramSettings.settings.SshKey, ProgramSettings.settings.SshPass); } } catch {} } sshCp.Connect(ProgramSettings.settings.SshPort); sshCp.Put(fname, ProgramSettings.settings.LstDir + "/" + fname); sshCp.Close(); return; }
public static bool SshMvAllFileSync(string host, string user, string password, string LocalFilePath, string remoteFilePath, out string errMes, Action <string> reportProcess, Action <string> reportError) { SshTransferProtocolBase sshCp = new Scp(host, user, password); sshCp.Connect(); bool outResult = SshMvAllFileSync(sshCp, LocalFilePath, remoteFilePath, out errMes, reportProcess, reportError); sshCp.Close(); return(outResult); }
private void btnTransfer_Click(object sender, EventArgs e) { if (host_input.Text == "") { MessageBox.Show("Please input a Host.", "Incomplete", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (user_input.Text == "") { MessageBox.Show("Please input a User.", "Incomplete", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } Scp sshCp = new Scp(host_input.Text, user_input.Text); if (password_input.Text != "") { sshCp.Password = password_input.Text; } else if (privatekey_input.FileName != "") { sshCp.AddIdentityFile(privatekey_input.FileName); } else { MessageBox.Show("Please input a password or private key file.", "Incomplete", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (serverlocation_input.Text == "") { MessageBox.Show("Please input a Server Side location to store the file.", "Incomplete", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } sshCp.OnTransferStart += new FileTransferEvent(sshCp_OnTransferStart); sshCp.OnTransferProgress += new FileTransferEvent(sshCp_OnTransferProgress); sshCp.OnTransferEnd += new FileTransferEvent(sshCp_OnTransferEnd); sshCp.Connect(); string destination = serverlocation_input.Text; if (!destination.EndsWith("/")) { destination += '/'; } destination += "dnadata/" + this.dest_folder; sshCp.To(this.interface_folder, destination, true); sshCp.Close(); MessageBox.Show("Transfer complete!", "Complete", MessageBoxButtons.OK, MessageBoxIcon.Information); }
static void testScp() { Scp s = new Scp("192.168.0.3", "root", "123456"); s.Connect(); if (s.Connected) { Console.WriteLine("connect server success"); s.From("/root/hello.txt", "D:\\"); } }
public void auxTransfer(RaspberryPi pi, string local, string remote) { Scp scp = new Scp(pi.getHostname(), pi.getUser(), pi.getPassword()); try { scp.Connect(); scp.From(remote, local); scp.Close(); } catch (Exception) { } }
/// <summary> /// Demonstrates the Scp class /// </summary> /// <param name="cmd">Either "to" or "from"</param> public static void Scp(string cmd) { GetInput(); string local = null, remote = null; if (cmd.ToLower().Equals("to")) { Console.Write("Local file: "); local = Console.ReadLine(); Console.Write("Remote file: "); remote = Console.ReadLine(); } else if (cmd.ToLower().Equals("from")) { Console.Write("Remote file: "); remote = Console.ReadLine(); Console.Write("Local file: "); local = Console.ReadLine(); } Scp scp = new Scp(); scp.OnConnecting += new FileTansferEvent(scp_OnConnecting); scp.OnStart += new FileTansferEvent(scp_OnProgress); scp.OnEnd += new FileTansferEvent(scp_OnEnd); scp.OnProgress += new FileTansferEvent(scp_OnProgress); try { if (cmd.ToLower().Equals("to")) { scp.To(local, host, remote, user, pass); } else if (cmd.ToLower().Equals("from")) { scp.From(host, remote, user, pass, local); } } catch (Exception e) { Console.WriteLine(e.Message); } }
public static void TransferFileFromMachine(string remoteFile, string localPath) { try { //Create a new SCP instance Scp scp = new Scp(MACHINE_IP, USER_NAME, PASSWORD); scp.Connect(); //Copy a file from remote SSH server to local machine scp.From(remoteFile, localPath); scp.Close(); } catch (Exception) { throw; } }
} // end BajarSCP public static void SubirSCP(string pServidor, string pUsuario, string pPassword, string pFileRemoto, string pFileLocal) { // instancia del objeto SCP Scp SCP = new Scp(pServidor, pUsuario, pPassword); try { // crear conexion SSH SCP.Connect(); // Subir el archivo SCP.To(pFileLocal, pFileRemoto, false); } catch (Exception ex) { throw ex; } finally { //cerrar conexion SCP SCP.Close(); } // end try } // end SubirSCP
/// <summary> /// SSH Secure copy protocol. /// </summary> /// <param name="sshConnection">SSH connection adapter.</param> public SshScp(SshConnection sshConnection) { _sshConnection = sshConnection; _scp = new Scp(sshConnection.Host, sshConnection.Username); // Get the authentication used. if (sshConnection.IsPrivateKeyAuthentication) { // For each private key file. foreach (PrivateKeyFile keyFile in sshConnection.PrivateKeyFiles) { // If a file exists. if (!String.IsNullOrEmpty(keyFile.PrivateKey) && !String.IsNullOrEmpty(keyFile.PrivateKeyPassword)) { // Set the file. _scp.AddIdentityFile(keyFile.PrivateKey, keyFile.PrivateKeyPassword); } // If a file exists. if (!String.IsNullOrEmpty(keyFile.PrivateKey)) { // Set the file. _scp.AddIdentityFile(keyFile.PrivateKey); } } } else { // If a password exists. if (!String.IsNullOrEmpty(sshConnection.Password)) { // Set the password. _scp.Password = sshConnection.Password; } } // Set the events. _scp.OnTransferStart += _sftp_OnTransferStart; _scp.OnTransferProgress += _sftp_OnTransferProgress; _scp.OnTransferEnd += _sftp_OnTransferEnd; }
public static bool InitSSH() { bool yes = false; if (LoadSettings()) { SshExec exec = new SshExec(SshSettings.server, SshSettings.user); sshexec = exec; SshTransferProtocolBase sshCp = new Scp(SshSettings.server, SshSettings.user); //А можно и так //sshCp = new Sftp(input.Host, input.User); sshsess = sshCp; yes = true; } else { yes = false; } return(yes); }
/// <summary> /// Dispose(bool disposing) executes in two distinct scenarios. /// If disposing equals true, the method has been called directly /// or indirectly by a user's code. Managed and unmanaged resources /// can be disposed. /// If disposing equals false, the method has been called by the /// runtime from inside the finalizer and you should not reference /// other objects. Only unmanaged resources can be disposed. /// </summary> protected virtual void Dispose(bool disposing) { // Check to see if Dispose has already been called. if (!this._disposed) { // Note disposing has been done. _disposed = true; // If disposing equals true, dispose all managed // and unmanaged resources. if (disposing) { if (_sshConnection != null) { _sshConnection.Dispose(); } } // Call the appropriate methods to clean up // unmanaged resources here. _scp = null; _sshConnection = null; } }
public async Task <bool> Initialize() { Console.WriteLine("Welcome to LanDiscordBot!\nBeginning initialization process..."); // Load settings Console.WriteLine("Loading bot settings..."); try { Settings = BotDao.LoadSettings(); } catch (Exception e) { Console.WriteLine(e.Message); } if (Settings == null) { Console.WriteLine("Invalid settings file. Creating new settings file."); Settings = new BotSettings(); BotDao.SaveSettings(Settings); } if (Settings.AuthToken.Length < 1) { Console.WriteLine("Invalid auth token! Please set your bot's auth token in config/bot.json."); return(false); } Console.WriteLine("Bot settings loaded."); // Login to Discord Console.WriteLine("Logging into Discord..."); try { await Client.LoginAsync(TokenType.Bot, Settings.AuthToken); } catch (Exception e) { Console.WriteLine(e); } if (Client.LoginState != LoginState.LoggedIn) { Console.WriteLine("Login failure! Please verify your auth token in config/bot.json."); return(false); } Console.WriteLine("Login successful!"); // Accounts init Console.WriteLine("Loading accounting..."); try { Accounts = AccountDao.LoadAccounts(); } catch (Exception e) { Console.WriteLine(e.Message); } if (Accounts == null) { Console.WriteLine("Invalid accounting file. Creating new accounting file."); if (Accounts == null) { Accounts = new AccountService(); } AccountDao.SaveAccounts(Accounts); } Accounts.Initialize(this); Console.WriteLine("Accounting loaded."); Scp.Initialize(); Dad.Initialize(); Chat.Initialize(); Highlights.Initialize(); Console.WriteLine("Starting Discord client..."); await Client.StartAsync(); Console.WriteLine("Finishing up initialization..."); await Client.SetGameAsync(Settings.PlayStatus); Console.WriteLine("Initialization complete!"); return(true); }
public static void RunExample() { try { SshConnectionInfo input = Util.GetInput(); string proto = GetProtocol(); SshTransferProtocolBase sshCp; if (proto.Equals("scp")) { sshCp = new Scp(input.Host, input.User); } else { sshCp = new Sftp(input.Host, input.User); } if (input.Pass != null) { sshCp.Password = input.Pass; } if (input.IdentityFile != null) { sshCp.AddIdentityFile(input.IdentityFile); } sshCp.OnTransferStart += new FileTransferEvent(sshCp_OnTransferStart); sshCp.OnTransferProgress += new FileTransferEvent(sshCp_OnTransferProgress); sshCp.OnTransferEnd += new FileTransferEvent(sshCp_OnTransferEnd); Console.Write("Connecting..."); sshCp.Connect(); Console.WriteLine("OK"); while (true) { string direction = GetTransferDirection(); if (direction.Equals("to")) { string lfile = GetArg("Enter local file ['Enter to cancel']"); if (lfile == "") { break; } string rfile = GetArg("Enter remote file ['Enter to cancel']"); if (rfile == "") { break; } sshCp.Put(lfile, rfile); } else { string rfile = GetArg("Enter remote file ['Enter to cancel']"); if (rfile == "") { break; } string lpath = GetArg("Enter local path ['Enter to cancel']"); if (lpath == "") { break; } sshCp.Get(rfile, lpath); } } Console.Write("Disconnecting..."); sshCp.Close(); Console.WriteLine("OK"); } catch (Exception e) { Console.WriteLine(e.Message); } }
// Use this for initialization void Start() { scp = GetComponent <Scp>(); scp.death_audio = GetComponent <AudioSource>(); }
protected override void RunWithSession(ref Session session) { string toDirectory = "/tmp"; Status = Messages.IN_PROGRESS; log.InfoFormat("{0} Upgrade...", Host.address); int sshdstate = 1; int sshport = 22; Dictionary <string, string> _servicearguments = new Dictionary <string, string>(); _servicearguments.Add("servicename", "sshd"); try { string rsvalue = XenAPI.Host.call_plugin(Host.Connection.Session, Host.opaque_ref, "serviceinfo.py", "getserviceinfo", _servicearguments); rsvalue = rsvalue.Replace("[", "").Replace("]", "").Replace("'", "").Replace("\\n", ""); string[] rsvalues = rsvalue.Split(','); if (rsvalues.Length > 1 && "0".Equals(rsvalues[1].Trim())) { log.InfoFormat("{0} sshd is running ...", Host.address); } if (rsvalues.Length > 1 && "3".Equals(rsvalues[1].Trim())) { log.InfoFormat("{0} sshd is stop, start sshd ...", Host.address); rsvalue = XenAPI.Host.call_plugin(Host.Connection.Session, Host.opaque_ref, "serviceinfo.py", "startserviceinfo", _servicearguments); rsvalue = rsvalue.Replace("[", "").Replace("]", "").Replace("'", "").Replace("\\n", ""); rsvalues = rsvalue.Split(','); if (rsvalues.Length > 1 && "0".Equals(rsvalues[1].Trim())) { sshdstate = 0; } else { throw new Exception(Messages.START_SSH_FAILED); } } //sshport = 7443; }catch (Exception) {} FileStream file = new FileStream(_fileName, FileMode.Open); string topfilename = Path.GetFileNameWithoutExtension(_fileName); System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(file); file.Close(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } log.InfoFormat("md5.......{0}", sb); SshTransferProtocolBase sshCp; //sshCp = new Sftp(Host.address, Host.Connection.Username); sshCp = new Scp(Host.address, Host.Connection.Username); sshCp.Password = Host.Connection.Password; log.InfoFormat("sshCp Connecting..."); sshCp.Connect(sshport); log.InfoFormat("sshCp Connecting OK ......."); String Programurl = Program.AssemblyDir; sshCp.Put(_fileName, toDirectory + "/" + Path.GetFileName(_fileName)); log.InfoFormat("cp Installation package ok......"); sshCp.Put(Programurl + "\\halsign_host_upgrade.py", "/etc/xapi.d/plugins/halsign_host_upgrade.py"); log.InfoFormat("cp halsign_host_upgrade.py ok......"); SshShell ssh = new SshShell(Host.address, Host.Connection.Username); ssh.Password = Host.Connection.Password; string productVersion = Host.ProductVersion; log.InfoFormat("sshshell Connecting..."); ssh.Connect(sshport); log.InfoFormat("sshshell Connecting ok..."); ssh.ExpectPattern = "#"; ssh.RemoveTerminalEmulationCharacters = true; //System.Console.WriteLine(); //Thread.Sleep(1000); //ssh.WriteLine("chmod 777 /etc/xapi.d/plugins/halsign_host_upgrade.py;echo $?"); //string output = ssh.Expect("#"); //log.InfoFormat(output); while (true) { ssh.WriteLine("chmod 777 /etc/xapi.d/plugins/halsign_host_upgrade.py;echo $?"); string output = ssh.Expect("#"); log.InfoFormat(output); if (output.IndexOf("rwxrwxrwx") > -1) { break; } ssh.WriteLine("ls -ld /etc/xapi.d/plugins/halsign_host_upgrade.py |awk '{print $1}'|sed 's/^[a-zA-Z-]//'"); output = ssh.Expect("#"); log.InfoFormat(output); if (output.IndexOf("rwxrwxrwx") > -1) { break; } } ssh.WriteLine("exit"); ssh.Close(); log.InfoFormat("sshshell Disconnecting OK....."); sshCp.Close(); log.InfoFormat("sshCp Disconnecting OK....."); if (sshdstate == 0) { XenAPI.Host.call_plugin(Host.Connection.Session, Host.opaque_ref, "serviceinfo.py", "stopserviceinfo", _servicearguments); } _arguments = new Dictionary <string, string>(); _arguments.Add("md5", sb.ToString()); _arguments.Add("filename", topfilename); _arguments.Add("toDirectory", toDirectory); Status = Messages.PLAN_ACTION_STATUS_HOST_UPGRADED; string value = XenAPI.Host.call_plugin(session, Host.opaque_ref, "halsign_host_upgrade.py", "main", _arguments); if (value.ToLower() == "true") { //base.RunWithSession(ref session); Status = Messages.PLAN_ACTION_STATUS_HOST_UPGRADED; } else if (",1,2,5,6,7,10,11,12,13,1001,1002,1003,1004,1005,1006,".IndexOf("," + value + ",") > -1) { value = value == "2" ? "1" : value; string Ms = "PATCH_UPGRADE_" + value; if (value.Equals("1")) { //Status = (string)XenAdmin.Messages.ResourceManager.GetString(Ms, resourceCulture); throw new Exception("PATCHOK_" + (string)XenAdmin.Messages.ResourceManager.GetString(Ms)); } else { throw new Exception((string)XenAdmin.Messages.ResourceManager.GetString(Ms)); } } else { throw new Exception(Messages.ERROR + ":" + value); } }