2022年2月14日 星期一

C# or Java 程式 利用 Powershell 開啟有密碼碼保護的Excel檔

本篇是C# or Java 程式 利用 Powershell 開啟有密碼碼保護的Excel檔

C# Example:
class Program
{
    static void Main(string[] args)
    {
        ProcessStartInfo psi = new ProcessStartInfo("powershell")
       {
            RedirectStandardInput = true,
            CreateNoWindow = true,
            UseShellExecute = false
        };

        using (var exeProcess = Process.Start(psi))
        {
            var input = exeProcess.StandardInput;
            input.WriteLine("$path = \"D:\\monitor.xlsx\"");
            input.WriteLine("$password = \"12345\"");
            input.WriteLine("$excel = New-Object -ComObject Excel.Application");
            input.WriteLine("$workbook = $excel.Workbooks.Open($path,$false,$false, 5,$password)");
            input.WriteLine("$excel.Visible = $true");
         }
    }
}


Java Example
public class OpenExcel {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		String[] list = {"powershell.exe"};
		ProcessBuilder pb = new ProcessBuilder(list);
		pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);	
		Process p = pb.start();
		
      OutputStream out = p.getOutputStream(); 
		PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out)));
		
		pw.println("$path = \"D:\\monitor.xlsx\"");
		pw.println("$password = \"12345\"");
		pw.println("$excel = New-Object -ComObject Excel.Application");
		pw.println("$workbook = $excel.Workbooks.Open($path,$false,$false, 5,$password)");
		pw.println("$excel.Visible = $true");
		pw.close();
		
		try {
			 p.waitFor();
			 p.destroy();
			} catch(InterruptedException ex) {
				
			}
	    
	}

}  

2019年3月29日 星期五

App自動檢測版本及更新 - Android

目前遇到 Android App 未佈到 Google Play,但可以由私有伺器服取得更新版,進而更新,參考到一些做法,記錄一下
1.首先在伺服器上建立一個version.json文件,提供給客戶端最新版本的信息,內容如下:

//json資料格式
{"code":"2.0","update":"最新版本apk的地址"}
2.在啟始頁中取得本機版本,並開啟連線取得伺服器的version.json,並解析出最新版本號與本機對比。(通常在與伺服器連線前,先Ping一下伺服器,來確保伺服器以及網路可用。)

3. 如果版本號不同,那就提示用戶版本需要升級。
4.當用戶同意升級,那麼就下載最新版本APK,並自動安裝。

大致流程就是這樣,接著上Code 。

通過 ping 伺服器,判斷伺服器是否可用。
/**
     * 通过ping判断是否可用
     * @return
     */
    public static boolean ping() {
        try {
            //服务器ip地址
            String ip = "***";
            Process p = Runtime.getRuntime().exec("ping -c 1 -w 100 " + ip);
            InputStream input = p.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuffer stringBuffer = new StringBuffer();
            String content;
            while ((content = in.readLine()) != null) {
                stringBuffer.append(content);
            }
            int status = p.waitFor();
            if (status == 0) {
                return true;
            }
        }
        catch (IOException e) {}
        catch (InterruptedException e) {}
        return false;
    }
從伺服器取得APP最新版本信息

/**
     * 获取最新版本信息
     * @return
     * @throws IOException
     * @throws JSONException
     */
    private String getVersion() throws IOException, JSONException {
        URL url = new URL("http://***/version.txt");
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setReadTimeout(8 * 1000);
        InputStream inputStream = httpURLConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String string;
        string = bufferedReader.readLine();
        //對json資料進行解析
        JSONObject jsonObject = new JSONObject(string);
        String strings = jsonObject.getString("code");
        return strings;
    }

彈出對話方塊,用戶按確定開始下庫最新版本APK,按取消不做任何動作。
/**
     * 彈出對話方塊
     */
    protected void showUpdataDialog() {
        AlertDialog.Builder builer = new AlertDialog.Builder(this) ;
        builer.setTitle("版本升級");
        builer.setMessage("軟體更新");
        //當按確定按鈕時,從伺服器下載新的apk,然後安装
        builer.setPositiveButton("確定", (dialog, which) -> downLoadApk());
        //當按取消按鈕時不做任何動作
        builer.setNegativeButton("取消", (dialogInterface, i) -> {});
        AlertDialog dialog = builer.create();
        dialog.show();
    }

開始從伺服器下載APK
    protected void downLoadApk() {
        //進度條
        final ProgressDialog pd;
        pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("正在下載更新");
        pd.show();
        new Thread(){
            @Override
            public void run() {
                try {
                    File file = getFileFromServer("http://***/v.apk", pd);
                    //安装APK
                    installApk(file);
                    pd.dismiss(); //結束進度條對話方塊
                } catch (Exception e) {
                }
            }}.start();
    }
public static File getFileFromServer(String path, ProgressDialog pd) throws Exception{
        //如果相等的話表示當前的sdcard掛載在手機上並且是可用的
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            //取得文件的大小
            pd.setMax(conn.getContentLength());
            InputStream is = conn.getInputStream();
            File file = new File(Environment.getExternalStorageDirectory(), "updata.apk");
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len ;
            int total=0;
            while((len =bis.read(buffer))!=-1){
                fos.write(buffer, 0, len);
                total+= len;
                //取得目前下載量
                pd.setProgress(total);
            }
            fos.close();
            bis.close();
            is.close();
            return file;
        }
        else{
            return null;
        }
    }

最後透過Intent動作啟動安裝APK
protected void installApk(File file) {
        Intent intent = new Intent();
        //執行動作
        intent.setAction(Intent.ACTION_VIEW);
        //報行的資料類型
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivity(intent);
    }
以上完畢。 參考網址: https://www.jianshu.com/p/2818d062a8f0

2016年12月28日 星期三

CentOS 架設 Git Server

1.安裝作業系統
2.建立 git 帳號
   Require a password to use this account 取消勾選
3.安裝SSH

   yum -y install openssh*
   service sshd start
   systemctl enable sshd.service
   systemctl status sshd.service

  測試ssh
  client:~ $ ssh root@remotehost

   產生金鑰:(Client)
 
   ssh-keygen -t rsa

   上傳 id_rsa.pub
 
   scp ~/.ssh/id_rsa.pub root@remotehost:/tmp

   接著設定伺服器上的SSH環境,連線到Server執行以下的指令:

   cd ~
   mkdir .ssh
   cat /tmp/id_rsa.pub >> ~/.ssh/authorized_keys
   chmod -R go= ~/.ssh

   PS: 1.下面兩個目錄的所有權必須是user,所屬組也應該是user,權限必須為700
             /home/user
             /home/user/.ssh
          2.下面金鑰文件的所有權必須是user,所屬組也應該是user,權限必須為644
             /home/user/.ssh/authorized_keys
          3.下面私鑰文件的所有權必須是user,所屬組也應該是user,權限必須為600
             /home/user/.ssh/id_rsa
          4.關閉 SELinux解決問題:
             暫時關閉(重啟後恢復)
             setenforce 0
             永久關閉(需要重啟)
             vi /etc/selinux/config
             SELINUX=disabled
           

         

   要注意以上的指令是與帳號對應的,如果要使用root來連線,則要在Server上以root登入後執行。完成了之後就可以關閉SSH的密碼登入,只允許使用金鑰來做登入。設定的方式是修改 /etc/ssh/sshd_config檔案的下述兩個參數:

 RSAAuthentication yes
 PubkeyAuthentication yes
 PasswordAuthentication no


設定Git環境
如果在安裝CentOS時沒有選擇安裝Development Tools的套件組合,則要先執行以下的指令,以便安裝Git套件:

  yum -y install git

安裝好了Git套件,可以先把安裝CentOS就建立好的git帳號對應的shell更改為git-shell,使連線進來的Session只能使用Git相關指令,減少資安的風險。一般git-shell都是在/usr/bin下,如果不確定可以先使用 which git-shell指令來查看實際安裝的路徑。

更改shell的方式是修改 /etc/passwd檔案,git的資訊應該位在檔案的最後一行,修改後的內容如下:

 git:x:1000:1000::/home/git:/usr/bin/git-shell

接下來要設定讓Client端可以使用git帳號來存取Server上的Repository,跟之前的步驟一樣,
把上傳到tmp下的金鑰檔加到git帳號所屬的authorized_keys檔案裡:

cd/home/git
mkdir .ssh
cat /tmp/id_rsa.pub >> .ssh/authorized_keys
chmod -R go= .ssh

再來就依據實際的需求建立一到多個空的Repository,指令示範如下:
cd /srv/git
mkdir project.git
cd project.git
git --bare init
chown -hR git:git /srv/git/project.git

回到 Client端,建立本地的Repository,但如果是第一次使用還沒進行初次的設定作業,要先執行以下的指令:

  git config --global user.email "you@example.com"
  git config --global user.name "You Name"

 接下來才是執行建立 Repository的指令,其中[path]是Repository要建立的路徑:

 cd [path]
mkdir myproject
cd myproject
git init

都準備好了之後,就可以做第一次的commit並push到Server上:

git add .
git commit -m 'initial commit'
git remote add origin git@remotehost:/srv/git/project.git
git push origin master

如果一切正常,就完成了在CentOS上架設 Git Server 的工作。

參考網址: http://wznote.blogspot.tw/2014/09/instal-git-server-in-centos.html
                  http://zqscm.qiniucdn.com/data/20130903005919/index.html
               



 

2016年8月25日 星期四

Docker data contianer 應用

假設我們要建立一個 mariaDB 的 container,但是我們希望資料不要儲存在自己或是本機裡面,我們可以獨立作一個 data container 出來讓 mariaDB 的 container 可以把資料儲存在 data container 裡面。

'建立資料容器
docker run --name dbdata mariadb echo "this is volume container"

'執行mariadb 使用 dbdata 容器
docker run --name mariadbdcs -v etc/localtime:/etc/localtime -v /backup/etc/mysql:/etc/mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=mypass --volumes-from dbdata -d mariadb

'執行 phpmyadmin
docker run --name myadmin -d --link mariadbdcs -e PMA_HOST=mariadbdcs -p 81:80 phpmyadmin/phpmyadmin

'備份資料
docker run --volumes-from dbdata -v $(pwd):/backup busybox tar cvf /backup/backup.tar /var/lib/mysql


'還原資料
1.建立資料容器
docker run --name dbdata mariadb echo "this is volume container"

2.還原資料
docker run --volumes-from dbdata -v $(pwd):/backup busybox sh -c "tar xvf /backup/backup.tar"

參考網址: https://chnbohwr.myds.me/wordpress/?cat=33

2016年8月16日 星期二

phpMyAdmin (on docker) 管理 mariadb (on docker)

執行 mariadb 容器
docker run --name mysqlserver -v /host/dir:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -p 3306:3306 -d mysql:latest
phpmyadmin 管理 mariadb 容器
docker run --name myadmin -d --link mysqlserver -p 8080:80 -e PMA_HOST=mysqlserver phpmyadmin/phpmyadmin
參考來源: https://github.com/phpmyadmin/docker/issues/23

2016年8月12日 星期五

Asp.Net Core ON Docker

主旨: Docker 上執行  ASP.NET Core 
作業系統 : CentOS 7
版本: .NET Core 1.0.0
準備事項 :
準備程式,本範例以ASP.NET Web API 為主

    mkdir YOKE
    cp {你的原始程式} YOKE
    cd YOKE

首先,為了構建一個可部署的.NET程序包先來運行dotnet publish。

    vi DockerFile //新增DockerFile
     
    DockerFile 內容:
   

   docker build -t yoke .  //建立新的docker image ( 命令最後有個點)
::   
    docker run -t -d -v  -p 8880:5000 yoke //背景執行容器,並把程5000port 指到本機的 8880port


開起瀏覽器
執行成功,收工

剪剪貼貼完成此篇,此篇只是要記錄自己實作的流程。


參考網址如下: