Exemplo n.º 1
0
        /// <summary>
        /// Polling of SFTP server to get the all registrations file.
        /// </summary>
        /// <param name="adminInfo"> DB Admin info</param>
        private void PollSFTPServer(DBAdminInfo adminInfo)
        {
            // call to sftp  server for getting all regisrations file
            string              filename   = null;
            SFTPHelper          sftpClient = new SFTPHelper(this.Logger);
            XmlNamespaceManager namespacemanager;

            try
            {
                this.Logger.Log(TraceEventType.Information, LoggingMessageId.DBSyncPollerGenericMessage, "Begin FCCDBSyncPoller - Poll() - making SFTPClint Call ");
                filename = sftpClient.GetAllXMLfileFromSFTP(adminInfo.FtpServerUrl, adminInfo.SFTPPath, adminInfo.FtpServerUserId, adminInfo.FtpServerPwd, Utils.GetOutputDirPathForConfigKey("FTPFileDownloadPath"));
                this.Logger.Log(TraceEventType.Information, LoggingMessageId.DBSyncPollerGenericMessage, "End FCCDBSyncPoller - Poll() - making SFTPClint Call ");

                XmlDocument xmlDocAll = new XmlDocument();
                xmlDocAll.PreserveWhitespace = true;
                xmlDocAll.Load(filename);

                namespacemanager = new XmlNamespaceManager(xmlDocAll.NameTable);
                namespacemanager.AddNamespace("m", xmlDocAll.DocumentElement.NamespaceURI);

                this.SyncManager.ParsePollResponse(adminInfo.Name, xmlDocAll.OuterXml, adminInfo.PublicKey);

                // Update Next Trasaction ID
                adminInfo.NextTransactionID = xmlDocAll.SelectSingleNode("//m:NextTransactionID", namespacemanager).InnerText;
                this.SyncManager.UpdateDBAdminInfo(adminInfo);
            }
            catch (Exception e)
            {
                this.Auditor.Audit(AuditId.DBSyncPollRequest, AuditStatus.Failure, 0, "FCCDBSyncPoller - Poll() - SFP file get Exception :" + e.ToString());
                this.Logger.Log(TraceEventType.Error, LoggingMessageId.DBSyncPollerGenericMessage, "FCCDBSyncPoller - Poll() - SFTP file get Exception :" + e.ToString());
            }
        }
Exemplo n.º 2
0
 public static void ChangeVersion()
 {
     //先更新版本号文件
     if (SFTPHelper.DownLoad(
             new SFTPHelper(sftpIp, sftpUserName, sftpPassword),
             GetVersionPath(),
             sftpPath + GameConfig.remoteFolder + "/" + versionName))
     {
         Debug.Log("下载版本文件成功");
         //最后一位+1
         VersionInfo versionInfo = JsonMapper.ToObject <VersionInfo>(File.ReadAllText(GetVersionPath()));
         versionInfo.version = VersionTools.AddAbVersion(versionInfo.version);
         //上传最新版本号文件
         if (SFTPHelper.UpLoad(
                 new SFTPHelper(sftpIp, sftpUserName, sftpPassword),
                 GetVersionPath(),
                 sftpPath + GameConfig.remoteFolder + "/" + versionName))
         {
             Debug.Log("上传版本文件成功");
         }
         else
         {
             Debug.LogError("上传版本文件失败");
         }
     }
     else
     {
         Debug.LogError("下载版本文件失败");
     }
 }
Exemplo n.º 3
0
        public async Task <ErrMessage> DEL_LENOVOSFTP()
        {
            ErrMessage rETURN = new ErrMessage();
            await Task.Run(() =>
            {
                SFTPHelper sftp   = new SFTPHelper("bjmft.lenovo.com", "22", "Ex_Ontim_P", "Ex_Ontim_P");
                string remotePath = "/856_Appendix/out/tmp";
                bool bl           = true;
                bool bl1          = true;
                Dictionary <string, string> dic = sftp.GetFileListFileName(remotePath, ".txt", ref bl);
                if (bl)
                {
                    dic = dic.OrderBy(r => r.Value).ToDictionary(r => r.Key, r => r.Value);
                    foreach (KeyValuePair <string, string> kvp in dic)
                    {
                        string extenname = kvp.Key;
                        sftp.Delete(remotePath + "/" + extenname);
                    }
                }
                Dictionary <string, string> dic1 = sftp.GetFileListFileName(remotePath, ".trigger", ref bl1);
                if (bl1)
                {
                    dic1 = dic1.OrderBy(r => r.Value).ToDictionary(r => r.Key, r => r.Value);
                    foreach (KeyValuePair <string, string> kvp in dic1)
                    {
                        string extenname = kvp.Key;
                        sftp.Delete(remotePath + "/" + extenname);
                    }
                }
            });

            rETURN.Err     = "执行完成";
            rETURN.success = true;
            return(rETURN);
        }
Exemplo n.º 4
0
 static void PublishBuild()
 {
     SFTPHelper.CleanFiles("*.*");
     AddressablesBundleBuildScript.AddFileToAddressables();
     AddressableAssetSettings.BuildPlayerContent();
     SFTPHelper.Upload("", "1.0.0");
 }
Exemplo n.º 5
0
    public static void UpLoadHotfixZip()
    {
        //先更新版本号文件
        if (SFTPHelper.DownLoad(
                new SFTPHelper(sftpIp, sftpUserName, sftpPassword),
                GetVersionPath(),
                sftpPath + GameConfig.remoteFolder + "/" + versionName))
        {
            Debug.Log("下载版本文件成功");
            VersionInfo versionInfo = JsonMapper.ToObject <VersionInfo>(File.ReadAllText(GetVersionPath()));

            //重命名压缩包,命名规则为当前版本号最后一位+1
            if (SFTPHelper.UpLoad(
                    new SFTPHelper(sftpIp, sftpUserName, sftpPassword),
                    GetHotfixZipPath(),
                    sftpPath + GameConfig.remoteFolder + "/" + VersionTools.AddAbVersion(versionInfo.version) + ".zip"))
            {
                Debug.Log("上传热更包成功");
            }
            else
            {
                Debug.LogError("上传热更包失败");
            }
        }
        else
        {
            Debug.LogError("下载版本文件失败");
        }
    }
Exemplo n.º 6
0
        private static void ProcessData(int identity, UserBaseEntity user, ISunnetLog loggerHelper,
                                        SFTPHelper sftp, string successPath, FileInfo file)
        {
            //将excel写回sftp
            if (!sftp.DirExist(successPath))
            {
                sftp.MakeDir(successPath);
            }
            sftp.Put(file.FullName, successPath + "/" + file.Name);

            string        tempPath = ConfigurationManager.AppSettings["TempPath"];
            EmailTemplete temp     = XmlHelper.GetEmailTemplete(tempPath, "EmailTemplate.xml");

            string subject = temp.Subject;
            string body    = string.Empty;

            body = temp.Body.Replace("{Name}", user.FirstName + " " + user.LastName);

            IEmailSender emailSender = ObjectFactory.GetInstance <IEmailSender>();

            emailSender.SendMail(user.PrimaryEmailAddress, subject, body);

            Console.WriteLine(string.Format("Result: Success. Identity: {0}", identity));
            loggerHelper.Info(string.Format("Result: Success. Identity: {0}", identity));
        }
Exemplo n.º 7
0
        ///****************************************************************************************************
        /// 函 数 名: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();
                }
            }
        }
Exemplo n.º 8
0
 public static SFTPHelper CreateSFTPHelper()
 {
     var helper = CallContext.GetData(typeof(SFTPHelper).FullName) as SFTPHelper;
     if (helper == null)
     {
         SFTPHelper = new BM.Common.SFTPHelper();
         CallContext.SetData(typeof(SFTPHelper).FullName, SFTPHelper);
     }
     return SFTPHelper;
 }
Exemplo n.º 9
0
 public void Test()
 {
     try
     {
         SFTPHelper sFTP = new SFTPHelper("122.224.250.39", "55535", "sftp01", "sftp01@1234");
         sFTP.Put(@"E:\home\hnn\test\t1.txt", "/root/geo/FrankWindowsServiceLogs/t1.txt");
     }
     catch (Exception ex)
     {
     }
 }
Exemplo n.º 10
0
        private void btnOpenSFTP_Click(object sender, EventArgs e)
        {
            SFTPHelper sftp         = new SFTPHelper("111.202.58.171", "abc", "123456", 20000, Path.Combine(System.Environment.CurrentDirectory, "sftpkey.ssh"), "123456");
            bool       connectState = sftp.Connected;

            lblSftpState.Text = sftp.SFTP_Message;
            if (connectState)
            {
                sftp.Put(Path.Combine(System.Environment.CurrentDirectory, "test_upload.txt"), "/upload/tripg/test_upload.txt");
                lblSftpState.Text = sftp.SFTP_Message;
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// 发送文件
        /// </summary>
        public void SendFileToLF()
        {
            try
            {
                //读取send文件夹,发送到LFsftp
                //读取文件列表
                string[] sendfiles = Directory.GetFiles(SFTPConstants.SendFilePath);
                if (sendfiles.Length > 0)
                {
                    for (int i = 0; i < sendfiles.Length; i++)
                    {
                        WMS_NikeReturnSFTP_Log log = new WMS_NikeReturnSFTP_Log();
                        log.SourceFileName = sendfiles[i];
                        log.Type           = "SendFile";

                        try
                        {
                            FileInfo file     = new FileInfo(sendfiles[i]);
                            string   filename = file.Name;
                            log.Str7  = SFTPConstants.sftpip;
                            log.Str8  = SFTPConstants.sftpport;
                            log.Str9  = SFTPConstants.sftpuser;
                            log.Str10 = SFTPConstants.sftppwd;
                            SFTPHelper sftp = new SFTPHelper(SFTPConstants.sftpip, SFTPConstants.sftpport, SFTPConstants.sftpuser, SFTPConstants.sftppwd);

                            //string sftpfilepath = SFTPConstants.sftpfilepath + @"\" + filename;
                            //发送文件
                            sftp.Put(sendfiles[i], filename);
                            log.ToFileName = SFTPConstants.SentFilePath + @"\" + filename;
                            log.Flag       = "Y";
                            log.ResultDesc = "发送成功";
                            FileCommon.MoveToCover(log.SourceFileName, log.ToFileName);
                        }
                        catch (Exception ex)
                        {
                            log.Flag       = "N";
                            log.ResultDesc = "发送失败:" + ex.Message.ToString();
                        }
                        new LogOperationService().AddNikeReturnSFTPLog(log);
                    }
                }
            }
            catch (Exception e)
            {
                WMS_NikeReturnSFTP_Log log = new WMS_NikeReturnSFTP_Log();
                log.Type       = "SendFile";
                log.Flag       = "N";
                log.ResultDesc = e.Message.ToString();
                new LogOperationService().AddNikeReturnSFTPLog(log);
            }
        }
Exemplo n.º 12
0
        public override bool Get()
        {
            //return true;
            try
            {
                string[] receivefiles = Directory.GetFiles(SFTPConstants.ReceiveFilePath);
                LogHelper.WriteLog(typeof(string), SFTPConstants.ReceiveFilePath, LogHelper.LogLevel.INFO);

                LogHelper.WriteLog(typeof(string), receivefiles.Length.ToString(), LogHelper.LogLevel.INFO);

                if (receivefiles.Length > 0)
                {
                    LogHelper.WriteLog(typeof(string), "Receive有文件就先处理文件", LogHelper.LogLevel.INFO);

                    //Receive有文件就先处理文件
                    Business();
                }

                //ConfigurationManager.AppSettings["SFTPPath"];

                SFTPHelper fTPHelper = new SFTPHelper(SFTPIP, SFTPort, SFTPUser, SFTPPwd);

                //下载主档
                var fileNames = fTPHelper.GetFileList(OUT_MASTER, "txt");
                foreach (var item in fileNames)
                {
                    bool results = fTPHelper.Get(OUT_MASTER + "//" + item, ReceiveFilePath + "//" + item);
                    if (results)
                    {
                        fTPHelper.Move(OUT_MASTER + "//" + item, OUT_MASTER_successful + "//" + item);
                    }
                }

                //下载订单
                var fileNames_Order = fTPHelper.GetFileList(OUT_TRANSACTION, "txt");
                foreach (var item in fileNames_Order)
                {
                    bool results = fTPHelper.Get(OUT_TRANSACTION + "//" + item, ReceiveFilePath + "//" + item);
                    if (results)
                    {
                        fTPHelper.Move(OUT_TRANSACTION + "//" + item, OUT_TRANSACTION_successful + "//" + item);
                    }
                }
            }
            catch (Exception ex)
            {
                //throw;
            }
            return(true);
        }
Exemplo n.º 13
0
 public static void UpLoadNewHash()
 {
     if (SFTPHelper.UpLoad(
             new SFTPHelper(sftpIp, sftpUserName, sftpPassword),
             GetNewHashPath(),
             sftpPath + GameConfig.remoteFolder + "/" + newHashName))
     {
         Debug.Log("上传hash成功");
     }
     else
     {
         Debug.LogError("上传hash失败");
     }
 }
Exemplo n.º 14
0
            /// <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();
            }
Exemplo n.º 15
0
        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();
        }
Exemplo n.º 16
0
        private static void WriteErrorMsg(SFTPHelper sftp, string localPath, string failedPath, FileInfo file, string errorMsg)
        {
            //在本地生成错误日志
            string loaclErrorLog = localPath + "/" + file.Name + ".log";

            Helper.WriteLog(loaclErrorLog, new ArrayList {
                errorMsg, "DateTime: " + DateTime.Now.ToString()
            });

            //将excel和错误日志写回sftp
            if (!sftp.DirExist(failedPath))
            {
                sftp.MakeDir(failedPath);
            }
            sftp.Put(loaclErrorLog, failedPath + "/" + file.Name + ".log");
            sftp.Put(file.FullName, failedPath + "/" + file.Name);
        }
Exemplo n.º 17
0
        private bool connToServer()
        {
            try
            {
                sshClient = new SshClient(ipAddress, port, userName, passward);

                sshClient.Connect();

                helper = new SFTPHelper(ipAddress, port, userName, passward);
                helper.Connect();
            }
            catch (Exception execption)
            {
                Console.Write(execption.Message);
            }

            return(helper.Connected);
        }
Exemplo n.º 18
0
 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);
 }
Exemplo n.º 19
0
        //---------------------------------------------------------------------
        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();
        }
Exemplo n.º 20
0
        public override bool Business()
        {
            try
            {
                SFTPHelper fTPHelper = new SFTPHelper(SFTPIP, SFTPort, SFTPUser, SFTPPwd);
                //读取文件列表
                string[] receivefiles = Directory.GetFiles(SFTPConstants.ReceiveFilePath);
                LogHelper.WriteLog(typeof(string), "开始处理文件", LogHelper.LogLevel.INFO);

                if (receivefiles.Length > 0)
                {
                    //TextHelper txthelper = new TextHelper();
                    for (int i = 0; i < receivefiles.Length; i++)
                    {
                        LogModel log = new LogModel();
                        log.SourceFileName = receivefiles[i];

                        FileInfo file        = new FileInfo(receivefiles[i]);
                        string   filename    = file.Name;
                        string   result      = "";//解析的错误提示
                        string   externumber = "";
                        try
                        {
                            List <string> txtlists = TextHelper.ReadTextFileToList(receivefiles[i]);//读取成list

                            //没有数据
                            if (txtlists.Count() > 0)
                            {
                                //可以处理多个接口文件
                                switch (txtlists[0].ToString().Substring(0, 9).Trim())
                                {
                                case "WMSSKU":    //PUMA推给我们的
                                    log.Type = "WMSSKU";
                                    result   = new ProductAccessor().AddProduct(txtlists, out externumber);
                                    break;

                                case "WMSASN":    //PUMA推给我们的 入库单
                                    log.Type = "WMSASN";
                                    result   = new ASNAccessor().GetInbound_ASNHD(txtlists, out externumber);
                                    break;

                                case "WMSORD":    //PUMA推给我们的 出库单
                                    log.Type = "WMSORD";
                                    result   = new ASNAccessor().GetInbound_ORDHD(txtlists, out externumber);
                                    break;

                                default:
                                    log.Type = "";
                                    result   = "未能从文件中识别出对应的接口";
                                    break;
                                }

                                if (result == "200")
                                {
                                    //解析成功,移动到success文件夹
                                    log.ToFileName  = SFTPConstants.SuccessFilePath + @"\" + log.Type + @"\" + filename;
                                    log.ResultDesc  = "解析成功";
                                    log.Externumber = externumber;
                                    log.Flag        = "Y";

                                    if (log.Type == "WMSSKU")
                                    {
                                        fTPHelper.Delete(OUT_MASTER + "//" + filename);
                                    }
                                    else
                                    {
                                        fTPHelper.Delete(OUT_TRANSACTION + "//" + filename);
                                    }
                                }
                                else
                                {
                                    if (log.Type != "")
                                    {
                                        if (result.Contains("数据库插入失败"))
                                        {
                                            log.ToFileName  = "";// SFTPConstants.SuccessFilePath + @"\" + log.Type + @"\" + filename;
                                            log.ResultDesc  = "解析失败:" + result;
                                            log.Externumber = externumber;
                                            log.Flag        = "E";
                                        }
                                        else
                                        {
                                            log.ToFileName  = SFTPConstants.FaildFilePath + @"\" + log.Type + @"\" + filename;//移动到解析失败文件夹
                                            log.ResultDesc  = "解析失败:" + result;
                                            log.Externumber = externumber;
                                            log.Flag        = "N";
                                        }
                                    }
                                    else
                                    {
                                        log.ToFileName  = SFTPConstants.ErrorFilePath + @"\" + filename;
                                        log.ResultDesc  = "解析失败:" + result;
                                        log.Externumber = externumber;
                                        log.Flag        = "N";
                                    }
                                }
                            }
                            else
                            {
                                log.ToFileName = SFTPConstants.ErrorFilePath + @"\" + filename;
                                log.Flag       = "N";
                                log.ResultDesc = "解析失败:文档中无数据";
                            }
                        }
                        catch (Exception ex)
                        {
                            //报错了放到error文件
                            log.ToFileName = SFTPConstants.ErrorFilePath + @"\" + filename;
                            log.Flag       = "N";
                            log.ResultDesc = "解析报错:" + ex.Message.ToString();
                        }
                        if (log.Flag == "E")
                        {//数据库失败再解析一次
                        }
                        else
                        {
                            LocalFileHelper.MoveToCover(log.SourceFileName, log.ToFileName);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(typeof(string), "处理文件错误" + ex.ToString(), LogHelper.LogLevel.INFO);

                //throw;
            }
            return(true);
        }
Exemplo n.º 21
0
        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;
            }
        }
Exemplo n.º 22
0
        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 ......");
        }