///**************************************************************************************************** /// 函 数 名:doBackup /// 输入参数:无 /// 返回值 :无 /// 功能描述: /// <summary> /// 进行文件备份,即从sftp指定目录上下载文件到本地并删除sftp上的相应文件 /// </summary> /// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /// 创 建 人:罗嗣扬 创建日期:2017-08-24 /// 修 改 人:罗嗣扬 修改日期:2017-08-25 ///**************************************************************************************************** public void doBackup() { //访问配置文件并获取默认配置 string sftp_ip = System.Configuration.ConfigurationManager.AppSettings["sftp_ip"]; string sftp_port = System.Configuration.ConfigurationManager.AppSettings["sftp_port"]; string sftp_username = System.Configuration.ConfigurationManager.AppSettings["sftp_username"]; string sftp_password = System.Configuration.ConfigurationManager.AppSettings["sftp_password"]; string sftp_path = System.Configuration.ConfigurationManager.AppSettings["sftp_path"]; string local_path = System.Configuration.ConfigurationManager.AppSettings["local_path"]; //创建一个sftp类对象 SFTPHelper sftpObj = null; try { //给sftp类对象赋值 sftpObj = new SFTPHelper(sftp_ip, sftp_port, sftp_username, sftp_password); //连接sftp服务器 sftpObj.Connect(); //获取指定sftp的文件列表 Array fileList = sftpObj.GetFileList(sftp_path).ToArray(); //创建一个代表不带路径的文件名的字符串 string shortFileName = ""; //遍历已经获取的sftp文件列表,逐个从sftp下载文件到本地并删除sftp上的相应文件 int i = 0; for (i = 0; i < fileList.Length; i++) { try { shortFileName = fileList.GetValue(i).ToString(); sftpObj.Get(sftp_path + shortFileName, local_path + shortFileName); sftpObj.Delete(sftp_path + shortFileName); } catch (Exception ex) { continue; } } log.Info("Ftp文件下载成功。下载文件数:" + i.ToString()); } catch (Exception ex) { log.Error("Ftp文件下载出现异常。", ex); } finally { if (sftpObj != null && sftpObj.Connected) { //断开sftp连接 sftpObj.Disconnect(); } } }
/// <summary> /// 上传文件到服务器 /// </summary> /// <param name="filename"></param> /// <param name="filecontent"></param> public void UploadFile() { UploadConfig uploadConfig = UploadConfig.getInstance(); string x = uploadConfig.linux_site.nginx_root; SFTPHelper sftp = new SFTPHelper(uploadConfig.linux_site.host, uploadConfig.linux_site.port, uploadConfig.linux_site.user, uploadConfig.linux_site.password); sftp.Connect(); string linuxpath = linuxroot + path; sftp.mkdir(linuxpath); linuxpath = uploadConfig.linux_site.nginx_root + filename; string windowspath = windowsroot + filename; bool uploadOK = sftp.Put(windowspath, linuxpath); sftp.Disconnect(); }
private void connect() { SFTPHelper helper = new SFTPHelper(TextBoxSQL.Text, 22, TextBoxUsername.Text, TextBoxPassword.Text); helper.Connect(); bool connect = helper.Connected; if (connect == true) { MessageBox.Show("连接成功!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("连接失败!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error); } helper.Disconnect(); }
public static bool DownLoad(SFTPHelper sftp, string localPath, string remotePath) { try { bool result = sftp.Connect(); result = sftp.Get(remotePath, localPath); return(result); } catch (Exception ex) { Debug.LogError("ex===" + ex.Message); } finally { sftp.Disconnect(); } return(false); }
//--------------------------------------------------------------------- private void DownFile(string szFileName, string szSaveTo) { bool bRet = false; listBox1.Items.Add("Download " + szFileName); listBox1.Refresh(); SFTPHelper sftp = new SFTPHelper(MyApp.HostIP, "root", "seiwa5588"); if (sftp.Connect()) { string szURL = "/var/www/html/version_update/" + szFileName; string szPath = MyApp.Path + szSaveTo; // 檢查資料夾是否存在?若不存在,則建立。 if (!Directory.Exists(szPath)) { DirectoryInfo szDir = Directory.CreateDirectory(szPath); } bRet = sftp.Get(szURL, szPath); if (bRet) { listBox1.Items.Add("Download " + szFileName + " ---- OK!"); if (szSaveTo == "version_update") { string srcFile = szPath + @"\" + szFileName; string destFile = System.Environment.CurrentDirectory + @"\" + szFileName; File.Copy(srcFile, destFile, true); File.Delete(srcFile); } } else { listBox1.Items.Add("Download " + szFileName + " ---- FAIL!"); } } sftp.Disconnect(); listBox1.Refresh(); }
protected void btnEnviar_Command(object sender, CommandEventArgs e) { try { LoDevices objLo = new LoDevices(); EnDevices objEn = new EnDevices(); DataTable dt = new DataTable(); int index = Convert.ToInt32(e.CommandArgument); Label rowid = (Label)grvListado.Rows[index].FindControl("lblrowid"); Label lblDip = (Label)grvListado.Rows[index].FindControl("lblDip"); dt = objLo.DevicesJson_Selecionar(Convert.ToInt32(rowid.Text)); string ruta = "/files/config.json"; // Setup Credentials and Server Information ConnectionInfo ConnNfo = new ConnectionInfo("104.248.211.185", 22, "root", new AuthenticationMethod[] { // Pasword based Authentication new PasswordAuthenticationMethod("root", "iota2019123"), // Key Based Authentication (using keys in OpenSSH Format) new PrivateKeyAuthenticationMethod("root", new PrivateKeyFile[] { new PrivateKeyFile(@"..\openssh.key", "passphrase") }), } ); // Execute a (SHELL) Command - prepare upload directory using (var sshclient = new SshClient(ConnNfo)) { sshclient.Connect(); using (var cmd = sshclient.CreateCommand("mkdir -p /tmp/uploadtest && chmod +rw /tmp/uploadtest")) { cmd.Execute(); Console.WriteLine("Command>" + cmd.CommandText); Console.WriteLine("Return Value = {0}", cmd.ExitStatus); } sshclient.Disconnect(); } // Upload A File using (var sftp1 = new SftpClient(ConnNfo)) { string uploadfn = "Renci.SshNet.dll"; sftp1.Connect(); sftp1.ChangeDirectory("/opt/prueba/"); using (var uplfileStream = System.IO.File.OpenRead(uploadfn)) { sftp1.UploadFile(uplfileStream, uploadfn, true); } sftp1.Disconnect(); } // Execute (SHELL) Commands using (var sshclient = new SshClient(ConnNfo)) { sshclient.Connect(); // quick way to use ist, but not best practice - SshCommand is not Disposed, ExitStatus not checked... Console.WriteLine(sshclient.CreateCommand("cd /tmp && ls -lah").Execute()); Console.WriteLine(sshclient.CreateCommand("pwd").Execute()); Console.WriteLine(sshclient.CreateCommand("cd /tmp/uploadtest && ls -lah").Execute()); sshclient.Disconnect(); } Console.ReadKey(); //using (var client = new SshClient("104.248.211.185", "root", "iota2019123")) //{ // client.Connect(); // //client.RunCommand("etc/init.d/networking restart"); // client.RunCommand ChangeDirectory("/opt/prueba/"); // using (var uplfileStream = System.IO.File.OpenRead(ruta)) // { // client.UploadFile(uplfileStream, ruta, true); // } // client.Disconnect(); // client.Disconnect(); //} // SendFileToServer.Send(ruta); return; FileInfo Archivo = new FileInfo(HttpContext.Current.Server.MapPath(ruta)); File.WriteAllText(HttpContext.Current.Server.MapPath(ruta), dt.Rows[0]["DJson"].ToString()); string destino = "/opt/prueba/"; string host = lblDip.Text.Trim(); string username = grvListado.DataKeys[index].Values["usuario"].ToString(); string password = Seguridad.DesEncriptar(grvListado.DataKeys[index].Values["clave"].ToString()); SFTPHelper sftp = new SFTPHelper(host, username, password); sftp.Connect(); sftp.Get(ruta, destino); sftp.Disconnect(); } catch (Exception ex) { throw ex; } }
static void Main(string[] args) { IoC.Init(); string filePath = string.IsNullOrEmpty(ConfigurationManager.AppSettings["UploadFile"]) ? "C:/log/cli/Upload/data_Process/" : ConfigurationManager.AppSettings["UploadFile"]; BUPProcessBusiness _bupProcessBusiness = new BUPProcessBusiness(); BUPTaskBusiness _bupTaskBusiness = new BUPTaskBusiness(); AutomationSettingBusiness _autoBusiness = new AutomationSettingBusiness(); List <AutomationSettingModel> processingAutomations = _autoBusiness.GetProcessingAutomationSettings(); UserBusiness _userBusiness = new UserBusiness(); ISunnetLog LoggerHelper = ObjectFactory.GetInstance <ISunnetLog>(); LoggerHelper.Info("start ......"); Console.WriteLine("start ......"); if (processingAutomations != null && processingAutomations.Count > 0) { List <UserBaseEntity> users = _userBusiness.GetUsers(processingAutomations.Select(r => r.CreatedBy).ToList()); foreach (AutomationSettingModel item in processingAutomations) { IEncrypt encrypt = ObjectFactory.GetInstance <IEncrypt>(); SFTPHelper sftp = new SFTPHelper(item.HostIp, item.Port, item.UserName, encrypt.Decrypt(item.PassWord), LoggerHelper); bool bconn = sftp.Connect(); if (bconn) { try { UserBaseEntity user = users.Find(r => r.ID == item.CreatedBy); if (user != null) { Dictionary <string, dynamic> dicType = GetDictionary(item); foreach (var type in dicType) { if (sftp.DirExist(type.Key)) { string localPath = filePath + (item.CommunityName + "/" + type.Key.Replace("/", "").Replace("\\", "")) + "/" + DateTime.Now.ToString("MM-dd-yyyy") + "/"; string failedPath = type.Key + "/Failed/" + DateTime.Now.ToString("MM-dd-yyyy") + "/"; string successPath = type.Key + "/Processed/" + DateTime.Now.ToString("MM-dd-yyyy") + "/"; //从sftp获取文件到本地目录 List <string> objList = new List <string>(); List <string> LocalFileList = new List <string>(); objList = sftp.GetFileList(type.Key, new string[] { ".xls", ".xlsx" }); if (objList.Count > 0) { Helper.CheckAndCreatePath(localPath); foreach (object obj in objList) { string fileUrl = obj.ToString(); string newFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "--" + fileUrl; sftp.Get(type.Key + "/" + fileUrl, localPath + "/" + newFileName); LocalFileList.Add(newFileName); sftp.DeleteFile(type.Key + "/" + fileUrl); } if (Directory.Exists(localPath)) { DirectoryInfo dr = new DirectoryInfo(localPath); foreach (FileInfo file in dr.GetFiles() .Where(r => r.Extension.ToLower() == ".xls" || r.Extension.ToLower() == ".xlsx" && LocalFileList.Contains(r.Name))) { Console.WriteLine(string.Format("Start processing {0}", file.FullName)); LoggerHelper.Info(string.Format("Start processing {0}", file.FullName)); //导入数据到BUP表 DataTable dt = new DataTable(); string errorMsg = ""; errorMsg = _bupProcessBusiness.InvalidateFile(file.FullName, type.Value.Count, type.Value.Type, out dt); if (!string.IsNullOrEmpty(errorMsg)) { Console.WriteLine(string.Format("Result: Error. Message: {0}", errorMsg)); LoggerHelper.Info(string.Format("Result: Error. Message: {0}", errorMsg)); WriteErrorMsg(sftp, localPath, failedPath, file, errorMsg); continue; } int identity = 0; string originFileName = file.Name.Substring(file.Name.IndexOf("--") + 2); //Automation 默认发送邀请 switch ((BUPType)type.Value.Type) { case BUPType.School: errorMsg = _bupProcessBusiness.ProcessSchool(dt, user.ID, originFileName, file.Name, user, out identity, BUPProcessType.Automation, item.CommunityId); break; case BUPType.Classroom: errorMsg = _bupProcessBusiness.ProcessClassroom(dt, user.ID, originFileName, file.Name, user, item.CommunityId, out identity, BUPProcessType.Automation); break; case BUPType.Class: errorMsg = _bupProcessBusiness.ProcessClass(dt, user.ID, originFileName, file.Name, user, out identity, BUPProcessType.Automation, item.CommunityId); break; case BUPType.Teacher: errorMsg = _bupProcessBusiness.ProcessTeacher(dt, user.ID, "1", originFileName, file.Name, user, out identity, BUPProcessType.Automation, item.CommunityId); break; case BUPType.Student: errorMsg = _bupProcessBusiness.ProcessStudent(dt, user.ID, originFileName, file.Name, user, out identity, BUPProcessType.Automation, item.CommunityId); break; case BUPType.CommunityUser: errorMsg = _bupProcessBusiness.ProcessCommunityUser(dt, user.ID, false, "1", originFileName, file.Name, user, item.CommunityId, out identity, BUPProcessType.Automation); break; case BUPType.CommunitySpecialist: errorMsg = _bupProcessBusiness.ProcessCommunityUser(dt, user.ID, true, "1", originFileName, file.Name, user, item.CommunityId, out identity, BUPProcessType.Automation); break; case BUPType.Principal: errorMsg = _bupProcessBusiness.ProcessPrincipal(dt, user.ID, false, originFileName, file.Name, "1", user, item.CommunityId, out identity, BUPProcessType.Automation); break; case BUPType.SchoolSpecialist: errorMsg = _bupProcessBusiness.ProcessPrincipal(dt, user.ID, true, originFileName, file.Name, "1", user, item.CommunityId, out identity, BUPProcessType.Automation); break; case BUPType.Parent: errorMsg = _bupProcessBusiness.ProcessParent(dt, user.ID, originFileName, file.Name, out identity, BUPProcessType.Automation); break; default: errorMsg = "Can not find this action: " + type.Value.Type; break; } if (!string.IsNullOrEmpty(errorMsg)) { Console.WriteLine(string.Format("Result: Error. Message: {0}", errorMsg)); LoggerHelper.Info(string.Format("Result: Error. Message: {0}", errorMsg)); WriteErrorMsg(sftp, localPath, failedPath, file, errorMsg); continue; } //执行数据导入操作 try { if (identity > 0) { ProcessHandler handler = new ProcessHandler(BUPTaskBusiness.Start); IAsyncResult asyncResult = handler.BeginInvoke(identity, user.ID, null, null); handler.EndInvoke(asyncResult); //此方法会等待异步执行完成后再往下执行 ProcessData(identity, user, LoggerHelper, sftp, successPath, file); } } catch (Exception ex) { Console.WriteLine(string.Format("Result: Error. Message: {0}", ex.Message)); LoggerHelper.Info(string.Format("Result: Error. Message: {0}", errorMsg)); WriteErrorMsg(sftp, localPath, failedPath, file, ex.Message); continue; } } } } } } sftp.Disconnect(); } else { LoggerHelper.Debug("Can not find user with the ID: " + item.CreatedBy + ". DateTime: " + DateTime.Now.ToString()); } } catch (Exception ex) { if (sftp.IsConnected) { sftp.Disconnect(); } Console.WriteLine(ex.Message); LoggerHelper.Info(string.Format("Result: Error. Message: {0}", ex.Message)); LoggerHelper.Debug(ex); } } else { LoggerHelper.Info("can not connect to the sftp server"); Console.WriteLine("can not connect to the sftp server"); } } } LoggerHelper.Info("end ......"); Console.WriteLine("end ......"); }