public static Dictionary <string, string> GetGdmXAuth(MeeGoDevice targetDevice)
        {
            Sftp sftp = null;

            try {
                sftp = new Sftp(targetDevice.Address, targetDevice.Username, targetDevice.Password);
                sftp.Connect();
                var files = sftp.GetFileList("/var/run/gdm/auth-for-" + targetDevice.Username + "*");
                sftp.Close();
                if (files.Count == 1)
                {
                    return(new Dictionary <string, string> ()
                    {
                        { "XAUTHLOCALHOSTNAME", "localhost" },
                        { "DISPLAY", ":0.0" },
                        { "XAUTHORITY", "/var/run/gdm/" + files[0] + "/database" }
                    });
                }
            } catch (Exception ex) {
                LoggingService.LogError("Error getting xauth via sftp", ex);
                if (sftp != null)
                {
                    try {
                        sftp.Close();
                    } catch (Exception ex2) {
                        LoggingService.LogError("Error closing sftp connection", ex2);
                    }
                }
            }
            return(null);
        }
Ejemplo n.º 2
0
        private void efwSimpleButton2_Click(object sender, EventArgs e)
        {
            try
            {
                string sftpURL       = "14.63.165.36";
                string sUserName     = "******";
                string sPassword     = "******";
                int    nPort         = 22023;
                string sftpDirectory = "/domalifefiles/files/product/domamall";

                // 저장 경로

                string LocalDirectory = "D:\\temp";  //Local directory from where the files will be uploaded
                string FileName       = "test1.jpg"; //File name, which one will be uploaded

                Sftp sSftp = new Sftp(sftpURL, sUserName, sPassword);

                sSftp.Connect(nPort);
                // sSftp.Mkdir("/domalifefiles/files/product/domamall/temp");
                sSftp.Put(LocalDirectory + "/" + FileName, sftpDirectory + "/" + FileName);
                sSftp.Close();
            }
            catch (Exception ex)
            {
                return;
            }
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Close the connection.
 /// </summary>
 public void Close()
 {
     if (_sftp.Connected)
     {
         _sftp.Close();
     }
 }
Ejemplo n.º 4
0
 public void PostRun( )
 {
     if (SftpRequest != null)
     {
         SftpRequest.Close();
     }
 }
Ejemplo n.º 5
0
 private void CloseSFTPConnection()
 {
     if (_wrapper != null)
     {
         _wrapper.Close();
     }
 }
Ejemplo n.º 6
0
        /// <summary>
        /// 推至遠程
        /// </summary>
        private void ToPut()
        {
            try
            {
                //fortify漏洞-----------------------------------------------add by bruce 20131220
                _password = AntiXSS.GetSafeHtmlFragment(_password);
                //fortify漏洞-----------------------------------------------add by bruce 20131220
                //開始進行SFTP程序
                _sftp = new Sftp(_hostName, _userName, _password);


                _sftp.Connect(_port);
                System.Threading.Thread.Sleep(3000);
                _sftp.Put(_fromFilePath, _toFilePath);
                System.Threading.Thread.Sleep(3000);
                _sftp.Close();

                //write log
                string msg = "";
                msg = "遠程" + _hostName + _toFilePath + ", 檔案已產生。";
                Console.WriteLine(msg);
                LogController.WriteLog("SimpleSftp.Put", msg);
            }
            catch (Exception ex)
            {
                LogController.WriteLog("SimpleSftp.Put", ex.ToString());
                throw ex;
            }
        }
Ejemplo n.º 7
0
 public void Close()
 {
     if (m_sshCp.Connected)
     {
         m_sshCp.Close();
     }
 }
Ejemplo n.º 8
0
        /* method that get the new order from sftp server */
        private void GetOrder(string filePath, IEnumerable <string> fileList)
        {
            // connection to sftp server and read all the list of file
            sftp.Connect();

            // download the files from the given list
            foreach (string file in fileList.Where(file => file != "." && file != ".."))
            {
                sftp.Get(SHIPMENT_DIR + '/' + file, filePath + "\\" + file);

                // after download the file delete it on the server (no need it anymore)
                ServerDelete.Delete(sftp.Host, sftp.Username, sftp.Password, SHIPMENT_DIR + '/' + file);
            }

            sftp.Close();
        }
Ejemplo n.º 9
0
        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();
        }
Ejemplo n.º 10
0
        /* the only function in the class that delete file on the sftp server */
        public static void Delete(string host, string username, string password, string fileName)
        {
            JSch js = new JSch();

            // declare sftp connection
            Sftp sftp = new Sftp(host, username, password);

            sftp.Connect();

            // Create a session with SFTP credentials
            Session session = js.getSession(sftp.Username, sftp.Host);

            // Get a UserInfo object
            UserInfo ui = new UInfo(sftp.Password);

            // Pass user info to session
            session.setUserInfo(ui);

            // Open the session
            session.connect();

            // Tell it is an SFTP
            Channel     channel = session.openChannel("sftp");
            ChannelSftp cSftp   = (ChannelSftp)channel;

            cSftp.connect();

            // Delete the file
            cSftp.rm(fileName);

            // disconnection
            channel.disconnect();
            cSftp.exit();
            sftp.Close();
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Uploads the file FTP.
        /// </summary>
        /// <param name="passKey">The pass key.</param>
        /// <param name="server">The server.</param>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        /// <param name="claim">The claim.</param>
        /// <param name="folder">The folder.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <returns>The <see cref="bool"/>.</returns>
        public bool UploadFileFTP(string passKey, string server, string username, string password, byte[] claim, string folder, string fileName)
        {
            if (!ValidationAndEncryptDecrypt.ValidateKey(passKey))
            {
                return(false);
            }

            string tempDir = "C:\\DrScribe\\GatewayEDI\\" + username + "\\claims\\";

            if (!Directory.Exists(tempDir))
            {
                Directory.CreateDirectory(tempDir);
            }

            try
            {
                var arraySize = claim.GetUpperBound(0);

                try
                {
                    if (File.Exists(tempDir + "\\" + fileName.Replace(".tmp", ".txt")))
                    {
                        File.Delete(tempDir + "\\" + fileName.Replace(".tmp", ".txt"));
                    }
                }
                catch (Exception e)
                {
                    WriteEventLogEntry(e);
                }

                FileStream fs = new FileStream(tempDir + "\\" + fileName.Replace(".tmp", ".txt"), FileMode.OpenOrCreate, FileAccess.Write);
                fs.Write(claim, 0, arraySize);
                fs.Close();

                SshTransferProtocolBase sshCp = new Sftp(server, username);
                sshCp.Password = password;

                sshCp.Connect();

                string serverFile = fileName.Replace(".tmp", ".txt");

                if (folder != string.Empty)
                {
                    serverFile = "/" + folder + "/" + serverFile;
                }

                sshCp.Put(tempDir + "\\" + fileName.Replace(".tmp", ".txt"), serverFile);

                sshCp.Close();
                sshCp.Destroy();

                File.Delete(tempDir + fileName.Replace(".tmp", ".txt"));
                return(true);
            }
            catch
            {
                return(false);
            }
        }
Ejemplo n.º 12
0
        public override DTSExecResult Execute(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log, object transaction)
        {
            ConnectionManager cSSH = getConnectionManager(connections, _SSHconnMgrName);
            List <KeyValuePair <string, string> > connParams = (List <KeyValuePair <string, string> >)cSSH.AcquireConnection(transaction);

            string host     = connParams.Find(t => t.Key == "Host").Value;
            string username = connParams.Find(t => t.Key == "Username").Value;
            string password = connParams.Find(t => t.Key == "Password").Value;
            int    port     = Convert.ToInt32(connParams.Find(t => t.Key == "Port").Value);

            if (_operation == SSHFTPOperation.SendFiles)
            {
                ConnectionManager       cSend      = getConnectionManager(connections, _sendFilesSourceConnectionManagerName);
                string                  sourceFile = cSend.AcquireConnection(transaction).ToString();
                SshTransferProtocolBase sshCp;
                sshCp          = new Sftp(host, username);
                sshCp.Password = password;
                string localFile  = sourceFile;
                string remoteFile = getRemotePathAndFile(_sendFilesDestinationDirectory, Path.GetFileName(sourceFile));
                try
                {
                    sshCp.Connect();
                    sshCp.Put(localFile, remoteFile);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    sshCp.Close();
                }
            }
            if (_operation == SSHFTPOperation.ReceiveFiles)
            {
                ConnectionManager       cReceive             = getConnectionManager(connections, _receiveFilesDestinationConnectionManagerName);
                string                  destinationDirectory = cReceive.AcquireConnection(transaction).ToString();
                SshTransferProtocolBase sshCp;
                sshCp          = new Sftp(host, username);
                sshCp.Password = password;
                try
                {
                    sshCp.Connect();
                    sshCp.Get(_receiveFilesSourceFile, destinationDirectory);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    sshCp.Close();
                }
            }

            return(DTSExecResult.Success);
        }
Ejemplo n.º 13
0
 private void exitBut_Click(object sender, EventArgs e)
 {
     try
     {
         sftp.Close();
         this.Close();
     }
     catch (Exception) { MessageBox.Show("Error exittingout of FTP Server"); }
 }
Ejemplo n.º 14
0
        public static int UploadFile(string server, string user, string pass, string origen, string rutadestino, string nombredestino)
        {
            int returnVal = 0;

            for (int i = 0; i < 5; i++)
            {
                Thread.sleep(2000);
                //sftpClient = new tss.Sftp(server, user);
                Sftp sftp = new Sftp(server, user, pass);
                sftp.OnTransferStart += new Tamir.SharpSsh.FileTransferEvent(sftp_OnTransferStart);
                sftp.OnTransferEnd   += new Tamir.SharpSsh.FileTransferEvent(sftp_OnTransferEnd);
                try
                {
                    String fromFile = origen;
                    String toFile   = rutadestino + "/" + nombredestino;

                    //connect to server
                    sftp.Connect();

                    //subir archivo
                    sftp.Put(fromFile, toFile);

                    Console.WriteLine("archivo publicado");

                    //close connection
                    sftp.Close();
                    i         = 5;
                    returnVal = 1;
                }

                catch (Exception ex)
                {
                    Thread.Sleep(3000);
                    Logger logger = LogManager.GetCurrentClassLogger();
                    logger = LogManager.GetCurrentClassLogger();

                    //close connection

                    logger.Error(ex);
                    sftp.Close();
                }
            }
            return(returnVal);
        }
Ejemplo n.º 15
0
        public bool GetFiles()
        {
            bool status = true;

            Sftp sftp = new Sftp(m_sftpSite, m_sftpSiteUserName);

            try
            {
                // add our private key to connect
                // put these in the config file
                sftp.AddIdentityFile(@"d:\apps\RSAKeys\opensshkey");

                // connect
                sftp.Connect();

                // get a directory list
                ArrayList rFiles = sftp.GetFileList(m_sftpSiteRemoteFolder);
                foreach (string file in rFiles)
                {
                    if (file.Equals(".") || file.Equals(".."))
                    {
                        continue;
                    }

                    // get the file and put in the watch folder to be processed
                    sftp.Get(m_sftpSiteRemoteFolder + file, m_moveToProcessFolder + file);

                    // update our database that we have downloaded the file from the server
                    // this.updateDb( file );

                    // delete the file on the remote server after pulling it over
                    // sftp.Delete(f);
                }

                sftp.Close();
                status = true;
            }
            catch (Tamir.SharpSsh.jsch.SftpException se)
            {
                LogMsg("NEXCEPTION:SftpMgr::GetFile():ECaught:" + se.Message);
            }
            catch (Tamir.SharpSsh.jsch.JSchException jse)
            {
                LogMsg("NEXCEPTION:SftpMgr::GetFile():ECaught:" + jse.Message);
            }
            catch (Tamir.SharpSsh.SshTransferException ste)
            {
                LogMsg("NEXCEPTION:SftpMgr::GetFile():ECaught:" + ste.Message);
            }
            catch (SystemException se)
            {
                LogMsg("NEXCEPTION:SftpMgr::GetFile():ECaught:" + se.Message);
            }

            return(status);
        } // getFile()
Ejemplo n.º 16
0
 public void Dispose()
 {
     if (sftp != null)
     {
         if (sftp.Connected)
         {
             sftp.Close();
         }
     }
 }
Ejemplo n.º 17
0
 public void ssh_command(string type, string host, string user, string password, string command)
 {
     if (type == "list dir")
     {
         Sftp sftp = new Sftp(host, user, password);
         try
         {
             sftp.Connect();
             ArrayList analyses = sftp.GetFileList(command);
             if (analyses.Count > 0)
             {
                 foreach (string run in analyses)
                 {
                     if (run.Length > 10)
                     {
                         this.stdRunsList.Items.Add(run);
                     }
                 }
                 count_label.Text = "Count: " + stdRunsList.Items.Count.ToString();
                 connected();
             }
         }
         catch
         {
             ConnectionError.Visible = true;
             pwdBox.ResetText();
         }
         finally
         {
             sftp.Close();
         }
     }
     else if (type == "kill")
     {
         ssh.Write(command);
         terminalThread.CancelAsync();
     }
     else
     {
         try
         {
             ssh   = new SshStream(host, user, password);
             abort = false;
             stopWatch.Start();
             terminalThread.RunWorkerAsync();
             checkThread.RunWorkerAsync();
             ssh.Write(command);
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message, "Minion - Stream Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
     }
 }
Ejemplo n.º 18
0
        public static void syncKioskoLinux(string host, string imageFolder, string videoFolder, string numTienda,
                                           ProgressTaskEventArgs e, int progActual, int razonCambio)
        {
            SshExec exec;
            SshTransferProtocolBase sshCp;

            exec           = new SshExec(host, kioskoUser);
            sshCp          = new Sftp(host, kioskoUser);
            exec.Password  = kioskoPass;
            sshCp.Password = kioskoPass;

            progActual += razonCambio;
            exec.Connect();
            e.UpdateProgress(progActual);

            progActual += razonCambio;
            sshCp.Connect();
            e.UpdateProgress(progActual);

            string imageLocalPath = String.Format("{0}{1}", kioskoRepository, imageFolder);
            string videoLocalPath = String.Format("{0}{1}", kioskoRepository, videoFolder);
            string xmlLocalPath   = String.Format("{0}{1}", pathToTemp, "kioskoXML");

            OneWayFolderSyncSSH imageSync = new OneWayFolderSyncSSH(exec, sshCp, imageLocalPath, kioskoPathToImages);
            OneWayFolderSyncSSH videoSync = new OneWayFolderSyncSSH(exec, sshCp, videoLocalPath, kioskoPathToVideos);
            OneWayFolderSyncSSH xmlSync   = new OneWayFolderSyncSSH(exec, sshCp, xmlLocalPath, kioskoPathToXML);
            XmlKioskoLinux      xmlKiosko = new XmlKioskoLinux(kioskoPathToImages, kioskoPathToVideos, pathToTemp, numTienda, exec);

            progActual += razonCambio * 2;
            imageSync.syncFiles("*.jpg");
            e.UpdateProgress(progActual);

            progActual += razonCambio * 2;
            videoSync.syncFiles("*.flv");
            e.UpdateProgress(progActual);

            progActual += razonCambio;
            xmlKiosko.generateServerXML(host);
            xmlKiosko.generateImageXML();
            xmlKiosko.generateVideoXML();
            e.UpdateProgress(progActual);

            progActual += razonCambio;
            xmlSync.syncFiles("*.xml");
            e.UpdateProgress(progActual);

            progActual += razonCambio;
            exec.Close();
            sshCp.Close();
            e.UpdateProgress(progActual);
        }
Ejemplo n.º 19
0
        static void Main(string[] args)
        {
            Sftp sftp = new Sftp("10.5.1.108", "developer", "pandora");

            //sftp.AddIdentityFile("[Path to Private kEY]");
            sftp.Connect();
            //sftp.Put(@"D:\temp\blog\feed.csv", "[PATH OF FILE ON SERVER]");
            //sftp.Delete("[PATH OF FILE ON SERVER]");
            Console.WriteLine(String.Join("\n", sftp.GetFileList("Desktop")));
            foreach (long size in sftp.GetFileSizes("Desktop"))
            {
                Console.WriteLine(Convert.ToString(size));
            }
            sftp.Close();
        }
Ejemplo n.º 20
0
        public static void Upload(RemoteDevice target, string sourcefile, string targetfile, bool overwrite)
        {
            var sftp = new Sftp(target.target.ToString(), target.username, target.password);


            sftp.Connect();
            if (!sftp.Connected)
            {
                //MonoDevelop.Ide.Gui.Dialogs.MultiMessageDialog dlg = new MultiMessageDialog();
                //dlg.AddMessage("Can not connect to Remote Host for File Transfer", "");
                //dlg.ShowAll();
                //return null;
            }

            sftp.Close();
        }
Ejemplo n.º 21
0
        public List <string> ClientSFtpBelBd()
        {
            Sftp oSftp = new Sftp(urlSFtp, userSFtp, passSFtp);

            oSftp.Connect(22);
            ArrayList     FileList = oSftp.GetFileList(dirBd);
            List <string> ls       = new List <string>();

            foreach (var i in FileList)
            {
                if (i is string f && f.Contains("mysql"))
                {
                    ls.Add(f);
                }
            }
            oSftp.Close();
            return(ls);
        }
Ejemplo n.º 22
0
        public void GetFileBdFromBel(string f, FileTransferEvent a, FileTransferEvent b, FileTransferEvent c)
        {
            var  e     = f;
            Sftp oSftp = new Sftp(urlSFtp, userSFtp, passSFtp);

            oSftp.Connect(22);
            try
            {
                oSftp.OnTransferProgress += a;
                //oSftp.OnTransferProgress += b;
                oSftp.OnTransferEnd += c;

                oSftp.Get($"{dirBd}/{f}");
            }
            catch
            {
            }
            oSftp.Close();
        }
Ejemplo n.º 23
0
        //WPF로 파일 업로드 (localfile : 컴퓨터 파일 경로, hwak : 확장자, std_no : 학번)
        //설치 순서 주의! - packages폴더에 dll이 있어야함.
        //사용시 https://sourceforge.net/projects/sharpssh/ 에서 다운한 파일 중 'Tamir.SharpSSH.dll'을 참조 후 누겟의 Tamir.SharpSSH 설치, 그 후 앞서 참조한 dll 참조 지우기
        private void Uploadimg(string localfile, string hwak, string std_no)
        {
            Sftp oSftp = null;

            try
            {
                SshExec se = new SshExec("l.bsks.ac.kr", "p201606023", "pp201606023");
                se.Connect(22);
                string dir = "/home/p201606023/public_html/image/";
                se.RunCommand("rm " + dir + std_no + ".jpg");
                se.RunCommand("rm " + dir + std_no + ".jpeg");
                se.RunCommand("rm " + dir + std_no + ".png");
                se.RunCommand("rm " + dir + std_no + ".gif");
                se.RunCommand("rm " + dir + std_no + ".JPG");
                se.RunCommand("rm " + dir + std_no + ".PNG");
                se.RunCommand("rm " + dir + std_no + ".GIF");
                se.Close();

                string _ftpURL       = "l.bsks.ac.kr";                        //Host URL or address of the SFTP server
                string _UserName     = "******";                          //User Name of the SFTP server
                string _Password     = "******";                         //Password of the SFTP server
                int    _Port         = 22;                                    //Port No of the SFTP server (if any)
                string _ftpDirectory = "/home/p201606023/public_html/image/"; //The directory in SFTP server where the files will be uploaded

                oSftp = new Sftp(_ftpURL, _UserName, _Password);
                oSftp.Connect(_Port);

                oSftp.Put(localfile, _ftpDirectory + std_no + "." + hwak);
            }
            catch (Exception ex)
            {
                MessageBox.Show("이미지 저장에 실패하였습니다.\n" + ex.Message + "::" + ex.StackTrace, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

                return;
            }
            finally
            {
                if (oSftp != null)
                {
                    oSftp.Close();
                }
            }
        }
Ejemplo n.º 24
0
        private void TransmitFiles()
        {
            string ftpFileName = Path.GetFileName(_CompressedArchiveFullPath);

            Sftp sftp = new Sftp(_FtpUrl, _UserName, _Password);

            sftp.Connect(_Port);

            if (DebugMode)
            {
                Logger.LogActivity("Upload skipped in Debug Mode");
            }
            else
            {
                sftp.Put(_CompressedArchiveFullPath, _FtpDirectory + "/" + ftpFileName);
                Logger.LogActivity("File {0} was successfully transmitted", _CompressedArchiveFullPath);
            }

            sftp.Close();
        }
Ejemplo n.º 25
0
        /// <summary>
        /// 遠程取得
        /// </summary>
        private void ToGet()
        {
            try
            {
                //fortify漏洞-----------------------------------------------add by bruce 20131220
                _password = AntiXSS.GetSafeHtmlFragment(_password);
                //fortify漏洞-----------------------------------------------add by bruce 20131220
                //開始進行SFTP程序
                _sftp = new Sftp(_hostName, _userName, _password);
                _sftp.Connect(_port);
                System.Threading.Thread.Sleep(3000);
                _sftp.Get(_fromFilePath, _toFilePath);
                System.Threading.Thread.Sleep(3000);
                _sftp.Close();

                //write log
                string   msg          = "";
                string   fullFilePath = _toFilePath;
                FileInfo oFile        = new FileInfo(fullFilePath); //e.g.: c:\\Test.txt
                if (oFile.Exists)
                {
                    msg = "本地" + _toFilePath + ", 檔案已產生。";
                    Console.WriteLine(msg);
                    LogController.WriteLog("SimpleSftp.Get", msg);
                }
                else
                {
                    msg = "本地" + _toFilePath + ", 檔案沒有產生。";
                    Console.WriteLine(msg);
                    LogController.WriteLog("SimpleSftp.Get", msg);
                }
            }
            catch (Exception ex)
            {
                LogController.WriteLog("SimpleSftp.Get", ex.ToString());
                throw ex;
            }
        }
Ejemplo n.º 26
0
        //=========================================== UpLoadFile ===========================================
        public bool sftpUpload(string fromFilePath, string toFilePath)
        {
            GlobalVM.Instance.updateDescription(String.Format("上传文件: {0} -> {1}", fromFilePath, toFilePath));
            bool bConnectSuccess = false;
            int  nTryTime        = 0;

            while (true)
            {
                if (nTryTime >= 3)
                {
                    break;
                }
                try
                {
                    ++nTryTime;
                    sftpClient = new Sftp(this.sftpServerIP, this.sftpUserID, this.sftpPassword);
                    sftpClient.Connect(16333);
                    bConnectSuccess = true;
                    break;
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }
            if (bConnectSuccess)
            {
                //sftpClient.OnTransferProgress
                sftpClient.Put(fromFilePath, toFilePath);
                sftpClient.Close();
            }
            else
            {
                MessageBox.Show("连接服务器失败!");
            }
            return(bConnectSuccess);
        }
Ejemplo n.º 27
0
        //----------------------------------------------------------------------------------
        /// <summary>
        ///
        /// </summary>
        /// <param name="target"></param>
        public static void OnTimerTraitement(object target)
        {
            CResultAErreur result = CResultAErreur.True;

            TimeSpan ts = DateTime.Now - m_lastDateDebutTraitementShort;

            if (m_bTraitementEnCours)
            {
                if (ts.TotalMinutes < 5)
                {
                    return;
                }
                else
                {
                    C2iEventLog.WriteErreur("CCamusatQowisioDataServeur : data processing >= 5 minutes");
                    return;
                }
            }

            m_bTraitementEnCours           = true;
            m_lastDateDebutTraitementShort = DateTime.Now;

            // Determine le mode du traitement SHORT/MEDIUM/FULL
            EModeTraitment modeTraitement = EModeTraitment.SHORT;

            ts = DateTime.Now - m_lastDateDebutTraitementMedium;
            if (ts.TotalMilliseconds >= c_nDelaiTraitementMedium)
            {
                modeTraitement = modeTraitement | EModeTraitment.MEDIUM;
                m_lastDateDebutTraitementMedium = DateTime.Now;
            }
            ts = DateTime.Now - m_lastDateDebutTraitementMedium;
            if (ts.TotalMilliseconds >= c_nDelaiTraitementFull)
            {
                modeTraitement = modeTraitement | EModeTraitment.FULL;
                m_lastDateDebutTraitementFull = DateTime.Now;
            }

            try
            {
                System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Lowest;
                try
                {
                    m_sessionClient = CSessionClient.CreateInstance();
                    result          = m_sessionClient.OpenSession(new CAuthentificationSessionServer(),
                                                                  "Qowisio XML data processing",
                                                                  ETypeApplicationCliente.Service);
                    if (!result)
                    {
                        C2iEventLog.WriteErreur("Working session openning error for CCamusatQowisioDataServeur");
                        return;
                    }

                    try
                    {
                        //Récupère les fichiers FTP
                        string strFTPserver         = CCamusatQowisioServeurRegistre.FTPServer;
                        string strFTPuser           = CCamusatQowisioServeurRegistre.FTPUser;
                        string strFTPpassword       = CCamusatQowisioServeurRegistre.FTPPassword;
                        int    nFTPport             = CCamusatQowisioServeurRegistre.FTPPort;
                        string strIncomingDirectory = CCamusatQowisioServeurRegistre.FTPIncomingDirectory;

                        List <string> listeFichiersATraiter = new List <string>();
                        ArrayList     listFiles             = null;

                        string strLastFile = new CDataBaseRegistrePourClient(m_sessionClient.IdSession).GetValeurString(c_strCleDernierFichierTraité, "");

                        Sftp ftp = new Sftp(strFTPserver, strFTPuser, strFTPpassword);
                        try
                        {
                            ftp.Connect(); /* Open the FTP connection */


                            listFiles = ftp.GetFileList(strIncomingDirectory);
                            listFiles.Sort();
                            listFiles.Reverse();

                            /*
                             *                              // constitue la liste des fichiers à traiter
                             *                              listFiles.AddRange(ftp.GetFiles());
                             *                              listFiles.Sort(new CFtpFileInfoComparer());
                             *                              listFiles.Reverse();*/

                            foreach (string strFtpFile in listFiles)
                            {
                                if (strFtpFile.CompareTo(strLastFile) <= 0)
                                {
                                    break;
                                }
                                string strWorkFile = WorkDir + "\\" + strFtpFile;
                                if (strFtpFile.ToUpper().EndsWith("XML"))
                                {
                                    if (!File.Exists(strWorkFile))
                                    {
                                        ftp.Get(strIncomingDirectory + "/" + strFtpFile, strWorkFile);
                                        //ftp.GetFile(fileInfo.Name, strWorkFile, false); /* download /incoming/file.txt as file.txt to current executing directory, overwrite if it exists */
                                        //ftp.RemoveFile(fileInfo.Name);
                                    }
                                    listeFichiersATraiter.Insert(0, strFtpFile);
                                }
                            }
                            if (listeFichiersATraiter.Count > 0)
                            {
                                new CDataBaseRegistrePourClient(m_sessionClient.IdSession).SetValeur(c_strCleDernierFichierTraité, listeFichiersATraiter[listeFichiersATraiter.Count - 1]);
                            }


                            ftp.Close();
                        }
                        catch (Exception ex)
                        {
                            C2iEventLog.WriteErreur("CCamusatQowisioDataServeur error openning FTP connection: " + ex.Message);
                        }
                        finally
                        {
                            ftp.Close();
                        }

                        // Traite la liste des fichiers à traiter
                        using (CContexteDonnee contexte = new CContexteDonnee(m_sessionClient.IdSession, true, false))
                        {
                            List <string> lstFichiersWork = new List <string>(Directory.GetFiles(WorkDir, "*.xml"));
                            lstFichiersWork.Sort();

                            //CCamusatQowisioDataServeur serveur = new CCamusatQowisioDataServeur(m_sessionClient.IdSession);
                            foreach (string strWorkFile in lstFichiersWork)
                            {
                                try
                                {
                                    string strNomFichier = Path.GetFileName(strWorkFile);

                                    // Traitement d'un fichier XML
                                    result = TraiteFichierQowisio(strWorkFile, contexte, modeTraitement);
                                    string strArchive = DoneDir + "\\" + strNomFichier;
                                    if (result)
                                    {
                                        MoveSafely(strWorkFile, ref strArchive);
                                    }
                                    else
                                    {
                                        strArchive = ErrorDir + "\\" + strNomFichier;
                                        MoveSafely(strWorkFile, ref strArchive);
                                        FileStream   stream = new FileStream(strArchive + ".Err", FileMode.CreateNew, FileAccess.Write);
                                        StreamWriter writer = new StreamWriter(stream);
                                        writer.Write(result.MessageErreur);
                                        writer.Close();
                                        stream.Close();
                                    }
                                }
                                catch (Exception e)
                                {
                                    C2iEventLog.WriteErreur("CCamusatQowisioDataServeur error while processing file : " + strWorkFile + " - " + e.Message);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        C2iEventLog.WriteErreur("CCamusatQowisioDataServeur error processing files : " + ex.Message);
                    }
                    finally
                    {
                        try
                        {
                            m_sessionClient.CloseSession();
                        }
                        catch { }
                    }
                }
                catch (Exception e)
                {
                    C2iEventLog.WriteErreur("CCamusatQowisioDataServeur error in OnTimerTraitement : " + e.Message);
                }
            }
            catch (Exception ex)
            {
                C2iEventLog.WriteErreur("CCamusatQowisioDataServeur error in OnTimerTraitement : " + ex.Message);
            }
            finally
            {
                m_bTraitementEnCours = false;
            }
        }
Ejemplo n.º 28
0
        // AB ZhaoYJ@2017-02-23 for user-defined dir to save log
        // private void DownloadThread(int[] selectedLogs)
        private void DownloadThread(int[] selectedLogs, string save_path)
        {
            try
            {
                status = SerialStatus.Reading;

                totalBytes = 0;
                tallyBytes = 0;
                // receivedbytes = 0;

                foreach (int a in selectedLogs)
                {
                    var entry = logEntries[a]; // mavlink_log_entry_t
                    totalBytes += entry.size;
                }

                // string[] nameParts = fileName.Split(' ', '-', ':', '/');

                // string save_file = @save_path + "1.bin";

                UpdateProgress(0, totalBytes, 0);

                // AB ZhaoYJ@2017-02-23 for user-defined dir to save log
                // download log files via SFTP, remove mavlink downloader because its slow speed
                // ========= start ==========
                try
                {
                    //string host = "192.168.7.2";
                    //string user = "******";
                    //string pass = "******";

                    string host = "11.0.0.1";
                    string user = "******";
                    string pass = "******";

                    Sftp sftp = new Sftp(host, user);
                    sftp.Password = pass;
                    sftp.Connect();

                    string path = "/var/APM/logs/";

                    foreach (int a in selectedLogs)
                    {
                        var entry = logEntries[a]; // mavlink_log_entry_t

                        DateTime fileDate = GetItemCaption(entry);

                        // string[] nameParts = fileName.Split(' ', '-', ':', '/');

                        AppendSerialLog(string.Format(LogStrings.FetchingLog, fileDate.ToString()));

                        string save_file = @save_path + "\\" + "[飞行日志]" + fileDate.Year + "年" + fileDate.Month + "月" + fileDate.Day + "日" + fileDate.Hour + "时" +
                                           fileDate.Minute + "分" + fileDate.Second + "秒" + ".BIN";
                        // string save_file = @save_path + "1.bin";

                        try
                        {
                            sftp.Get(path + entry.id.ToString() + ".BIN", save_file);
                        }
                        catch (Exception ex)
                        {
                            CustomMessageBox.Show("日志文件 [" + entry.id.ToString() + " " + fileDate + "] 可能已不存在,请重新刷新日志列表", Strings.ERROR);
                        }
                        // var logname = GetLog(entry.id, fileName);
                        // CreateLog(logname);

                        tallyBytes += logEntries[a].size;
                        // receivedbytes = 0;
                        UpdateProgress(0, totalBytes, tallyBytes);
                    }
                    sftp.Close();
                    CustomMessageBox.Show("日志文件下载成功", Strings.Done);
                }
                catch (Exception ex)
                {
                    CustomMessageBox.Show(ex.Message, Strings.ERROR);
                }
                // ========= end ==========


                UpdateProgress(0, totalBytes, totalBytes);
                AppendSerialLog("=================================================");

                AppendSerialLog("\n所有日志文件下载成功.");
                Console.Beep();
            }
            catch (Exception ex)
            {
                AppendSerialLog("Error in log " + ex.Message);
            }

            RunOnUIThread(() =>
            {
                BUT_DLall.Enabled   = true;
                BUT_DLthese.Enabled = true;
                status = SerialStatus.Done;
            });
        }
Ejemplo n.º 29
0
        private void BUT_DLall_Click(object sender, EventArgs e)
        {
#if HL
            //Added by HL below
            try
            {
                //string host = "192.168.7.2";
                //string user = "******";
                //string pass = "******";

                string host = "11.0.0.1";
                string user = "******";
                string pass = "******";

                Sftp sftp = new Sftp(host, user);
                sftp.Password = pass;
                sftp.Connect();

                string    path      = "/var/APM/logs/";
                ArrayList arrayList = sftp.GetFileList(path);
                foreach (var item in arrayList)
                {
                    if (item is string)
                    {
                        string fileName = item as string;
                        if (fileName.EndsWith(".BIN"))
                        {
                            sftp.Get(path + fileName, save_dir);
                            break;
                        }
                    }
                }

                sftp.Close();
                CustomMessageBox.Show("日志文件下载成功,请到LogData目录下查看", Strings.OK);
            }
            catch (Exception ex)
            {
                CustomMessageBox.Show(ex.Message, Strings.ERROR);
            }
            //Added by HL above
#else
            // AB ZhaoYJ@2017-02-23 for save log into dedicated path and file name
            // ========= start =========
            if (status == SerialStatus.Done)
            {
                if (CHK_logs.Items.Count == 0)
                {
                    // try again...
                    LoadLogList();
                    return;
                }
                BUT_DLall.Enabled   = false;
                BUT_DLthese.Enabled = false;
                int[] toDownload = GetAllLogIndices().ToArray();

                try
                {
                    Directory.CreateDirectory(Settings.Instance.LogDir);
                }
                catch (Exception ex)
                {
                    AppendSerialLog(string.Format(LogStrings.LogDirectoryError, Settings.Instance.LogDir) + "\r\n" + ex.Message);
                    return;
                }

                // AB ZhaoYJ@2017-03-28 for user-defined dir to save log
                // ========= start =========
                string save_dir = "";

                // get save path from user
                var first_entry = logEntries[toDownload[0]]; // mavlink_log_entry_t

                DateTime fristFileDate = GetItemCaption(first_entry);

                string save_file = "[飞行日志]" + fristFileDate.Year + "年" + fristFileDate.Month + "月" + fristFileDate.Day + "日" + fristFileDate.Hour + "时" +
                                   fristFileDate.Minute + "分" + fristFileDate.Second + "秒" + ".BIN";

                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.RestoreDirectory = true;
                saveFileDialog1.Filter           = "飞行日志|*.BIN";
                saveFileDialog1.Title            = "保存飞行日志文件";
                saveFileDialog1.FileName        += save_file;
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    save_dir = Path.GetDirectoryName(saveFileDialog1.FileName.ToString());
                }
                else
                {
                    return;
                }

                AppendSerialLog(string.Format(LogStrings.DownloadStarting, save_dir));

                System.Threading.Thread t11 = new System.Threading.Thread(
                    delegate()
                {
                    DownloadThread(toDownload, save_dir);
                });
                t11.Name = "Log Download All thread";
                t11.Start();
            }
            // ========= end =========
#endif
        }
Ejemplo n.º 30
0
        public bool nikto_get_result(string file, string localOuputFile)
        {
            XPathNavigator    nav;
            XPathNavigator    nav1;
            XPathDocument     docNav;
            XPathNodeIterator NodeIter1;
            String            strExpression1;

            try
            {
                Sftp ftp;
                ftp = new Sftp("111.222.333.444", "root", "toor");  //Hardcoded

                ftp.OnTransferStart    += new FileTransferEvent(ftp_OnTransferStart);
                ftp.OnTransferProgress += new FileTransferEvent(ftp_OnTransferProgress);
                ftp.OnTransferEnd      += new FileTransferEvent(ftp_OnTransferEnd);

                ftp.Connect(22);

                ftp.Get("/home/root/tools/nikto-2.1.4/" + file, localOuputFile);    //Hardcoded

                ftp.Close();
            }
            catch (Exception ex)
            {
                Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("Exception = {0} / {1}", ex.Message, ex.InnerException == null ? "" : ex.InnerException.Message));
                return(false);
            }

            Utils.Helper_Trace("XORCISM PROVIDER NIKTO", "Loading the xml document");

            /* SAMPLE of XML structure
             *
             *  <?xml version="1.0" ?>
             *  <!DOCTYPE niktoscan SYSTEM "/usr/share/doc/nikto/nikto.dtd">
             *  <niktoscan options="-Format XML -o result_634550673449458000_35287174.xml -host TARGET -T x" version="2.1.1" nxmlversion="1.1">
             *  <scandetails targetip="IP_target" targethostname="URL_Target" targetport="80" targetbanner="gws" starttime="DATE/time"
             *      sitename="http://*****:*****@targetip | /niktoscan/scandetails/@targethostname | /niktoscan/scandetails/@targetport | /niktoscan/scandetails/@targetbanner | /niktoscan/scandetails/@sitename | /niktoscan/scandetails/@siteip";
                    NodeIter1      = nav1.Select(strExpression1);
                    while (NodeIter1.MoveNext())
                    {
                        // For headers
                        switch ((string)NodeIter1.Current.Name)
                        {
                        //Hardcoded
                        case "targetip":
                            Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} XML PARSE - TARGET IP : [{1}] ", m_jobId, NodeIter1.Current.Value));
                            break;

                        case "targethostname":
                            Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} XML PARSE - TARGET HOSTNAME : [{1}] ", m_jobId, NodeIter1.Current.Value));
                            break;

                        case "targetport":
                            Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} XML PARSE - TARGET PORT : [{1}] ", m_jobId, NodeIter1.Current.Value));
                            break;

                        case "targetbanner":
                            Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} XML PARSE - TARGET BANNER : [{1}] ", m_jobId, NodeIter1.Current.Value));
                            break;

                        case "sitename":
                            Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} XML PARSE - SITE NAME : [{1}] ", m_jobId, NodeIter1.Current.Value));
                            break;

                        case "siteip":
                            Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} XML PARSE - SITE IP : [{1}] ", m_jobId, NodeIter1.Current.Value));
                            break;
                        }
                        list_parse.Add((string)NodeIter1.Current.Value);
                    }
                    ;

                    //Hardcoded
                    strExpression1 = "/niktoscan/scandetails/item/@id | /niktoscan/scandetails/item/@osvdbid | /niktoscan/scandetails/item/@osvdblink | /niktoscan/scandetails/item/description | /niktoscan/scandetails/item/uri | /niktoscan/scandetails/item/namelink | /niktoscan/scandetails/item/iplink";
                    NodeIter1      = nav1.Select(strExpression1);

                    //TODO

                    /*
                     * INFORMATION newInfo = null;
                     * while (NodeIter1.MoveNext())
                     * {
                     *  // For each Items
                     *  switch ((string)NodeIter1.Current.Name)
                     *  {
                     *      case "id":
                     *          Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} XML PARSE - ITEM ID : [{1}] ", m_jobId, NodeIter1.Current.Value));
                     *          if (newInfo != null)
                     *          {
                     *              try
                     *              {
                     *                  m_model.AddToINFORMATION(newInfo);
                     *                  m_model.SaveChanges();
                     *              }
                     *              catch (Exception ex)
                     *              {
                     *                  Utils.Helper_Trace("XORCISM PROVIDER WHATWEB", "JobID:" + m_jobId + "Exception adding newInfo = " + ex.Message + " " + ex.InnerException);
                     *              }
                     *          }
                     *          newInfo = new INFORMATION();
                     *          newInfo.Title = NodeIter1.Current.Value;
                     *          newInfo.JobID = m_jobId;
                     *          break;
                     *      case "osvdbid":
                     *          Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} XML PARSE - OSVDB ID : [{1}] ", m_jobId, NodeIter1.Current.Value));
                     *
                     *          break;
                     *      case "osvdblink":
                     *          Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} XML PARSE - OSVDB LINK : [{1}] ", m_jobId, NodeIter1.Current.Value));
                     *          break;
                     *      case "description":
                     *          Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} XML PARSE - DESCRIPTION : [{1}] ", m_jobId, NodeIter1.Current.Value));
                     *          newInfo.Description = NodeIter1.Current.Value;
                     *          //Todo: parse regex CAN-2004-0885. OSVDB-10637
                     *          break;
                     *      case "uri":
                     *          Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} XML PARSE - URI : [{1}] ", m_jobId, NodeIter1.Current.Value));
                     *          break;
                     *      case "namelink":
                     *          Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} XML PARSE - NAME LINK : [{1}] ", m_jobId, NodeIter1.Current.Value));
                     *          newInfo.Url = NodeIter1.Current.Value;
                     *          break;
                     *      case "iplink":
                     *          Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} XML PARSE - IP LINK : [{1}] ", m_jobId, NodeIter1.Current.Value));
                     *          break;
                     *  }
                     *  list_parse.Add((string)NodeIter1.Current.Value);
                     * };
                     * //Last one
                     * if (newInfo != null)
                     * {
                     *  try
                     *  {
                     *      m_model.AddToINFORMATION(newInfo);
                     *      m_model.SaveChanges();
                     *  }
                     *  catch (Exception ex)
                     *  {
                     *      Utils.Helper_Trace("XORCISM PROVIDER WHATWEB", "JobID:" + m_jobId + "Exception adding last newInfo = " + ex.Message + " " + ex.InnerException);
                     *  }
                     * }
                     */

                    //Hardcoded
                    strExpression1 = "/niktoscan/scandetails/statistics/@elapsed | /niktoscan/scandetails/statistics/@itemsfound | /niktoscan/scandetails/statistics/@itemstested | /niktoscan/statistics/@hoststotal";
                    NodeIter1      = nav1.Select(strExpression1);
                    while (NodeIter1.MoveNext())
                    {
                        // For each statictics
                        switch ((string)NodeIter1.Current.Name)
                        {
                        case "elapsed":
                            Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} XML PARSE - ELAPSED : [{1}] ", m_jobId, NodeIter1.Current.Value));
                            break;

                        case "itemsfound":
                            Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} XML PARSE - ITEMS FOUND : [{1}] ", m_jobId, NodeIter1.Current.Value));
                            break;

                        case "itemstested":
                            Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} XML PARSE - ITEMS TESTED : [{1}] ", m_jobId, NodeIter1.Current.Value));
                            break;

                        case "targetbanner":
                            Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} XML PARSE - TARGET BANNER : [{1}] ", m_jobId, NodeIter1.Current.Value));
                            break;

                        case "hoststotal":
                            Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} XML PARSE - NUMBER OF HOST : [{1}] ", m_jobId, NodeIter1.Current.Value));
                            break;
                        }
                        list_parse.Add((string)NodeIter1.Current.Value);
                    }
                    ;
                }
                catch (System.Exception ex)
                {
                    Utils.Helper_Trace("XORCISM PROVIDER NIKTO", "JobID:" + m_jobId + "Exception Parsing XML PLUGIN'S = " + ex.Message + " " + ex.InnerException);
                }
            }
            catch (System.Exception ex)
            {
                Utils.Helper_Trace("XORCISM PROVIDER NIKTO", "JobID:" + m_jobId + "Exception LOADING XML " + localOuputFile + "= " + ex.Message + " " + ex.InnerException);

                //Retry
                Thread.Sleep(120000);   //Hardcoded
                nikto_get_result(file, localOuputFile);
            }
            return(true);
        }